Gusti
Gusti

Reputation: 71

Mongoose: Find all documents with array field which is included in another array

So the example for this would be something like this:

Requesting to do a search on the following array:

    ['banana', 'apple', 'orange', 'mango']

As for my database, I have a Recipe collection which contains a field ingredints - being an Array.

Document #1:

... ingredients: ['banana', 'apple'] ...

Document #2:

... ingredients: ['banana', 'apple', 'orange'] ...

Document #3:

... ingredients: ['apple', 'orange', 'kiwi'] ...

The output of the query should return Document #1 and Document #2. (Document #3 containing kiwi which is not included in the initial array).

Upvotes: 0

Views: 656

Answers (1)

mickl
mickl

Reputation: 49945

You can use below aggregation:

db.col.aggregate([
    {
        $addFields: {
            matchingElements: { $setIntersection: [ ['banana', 'apple', 'orange', 'mango'], "$ingredients" ] }
        }
    },
    {
        $redact: {
            $cond: {
                if: { $eq: [ { $size: "$ingredients" }, { $size: "$matchingElements" } ] },
                then: "$$KEEP",
                else: "$$PRUNE"
            }
        }
    },
    {
        $project: {
            matchingElements: 0
        }
    }
])

$setIntersection will give you all the items from ingredients that are present in your array. Then you can use $redact to check if matchingElements has the same size as ingredients which means that all elements match.

Upvotes: 1

Related Questions