简体   繁体   中英

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM