arxenix
arxenix

Reputation: 180

MongoDB match documents with all elements in a given array

I have an array

solvedProblemIds = [0,2]

and I want to query for documents that have ALL of the elements in their requiredProblems array inside the solvedProblemIds array.

for example, if these are my documents:

{
    id: 0,
    name: "Problem 1",
    points: 10,
    description: "Problem 1 desc",
    requiredProblems: []
},
{
    id: 1,
    name: "Problem 2",
    points: 10,
    description: "Problem 2 desc",
    requiredProblems: [0]
},
{
    id: 2,
    name: "Problem 3",
    points: 10,
    description: "Problem 3 desc",
    requiredProblems: [0]
},
{
    id: 3,
    name: "Problem 4",
    points: 10,
    description: "Problem 4 desc",
    requiredProblems: [0, 2]
},
{
    id: 4,
    name: "Problem 5",
    points: 10,
    description: "Problem 5 desc",
    requiredProblems: [0, 1, 2, 3]
}

The query should match the documents with id 3, 2, 1, and 0. I looked at the $in selector, but it only requires ONE element to be in the array, not all.

Upvotes: 0

Views: 73

Answers (1)

KangarooWest
KangarooWest

Reputation: 846

There's no operator that works out of the box for determining a subset. You can either do an aggregation (I haven't thought about how) or the following:

{ $not: { $elemMatch: { $nin: [0, 2] } } }

This is finding documents such that there exists no elements that are not in [0, 2].

Upvotes: 1

Related Questions