简体   繁体   中英

Find documents that have matching elements between arrays

I am using match within aggregate to return any documents who have a matching elements with an embedded array and another array. An example:

Documents

    {
        name: "Frank",
        favoriteColors: ["red", "pink", "orange"]
    }
    
    {
        name: "Bob",
        favoriteColors: ["blue", "red", "green"]
    }

Array

    let colors = ["blue", "maroon"];

So, basically, I want to find every person (document) that has either blue or maroon in their favorite colors.

Use the $in operator to filter a range of values.

Insert script -

db.collection.insertMany([
{
    "name": "Frank",
    "favoriteColors": ["red", "pink", "orange"]
},
{
    "name": "Bob",
    "favoriteColors": ["blue", "red", "green"]
}]);

The query -

var query = {
    favoriteColors: {
        $in: ["blue", "maroon"]
    }
};

db.collection.find(query);

Outputs -

/* 1 */
{
    "_id" : ObjectId("5f12a14db00513b7c6ab6203"),
    "name" : "Bob",
    "favoriteColors" : [ 
        "blue", 
        "red", 
        "green"
    ]
}

something like this:

db.myCollection.find({ favoriteColors: { $in: ["blue", "maroon"] } })

you can find more documentation here https://docs.mongodb.com/manual/reference/operator/query/in/#use-the-in-operator-to-match-values-in-an-array

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