简体   繁体   English

查找在 arrays 之间具有匹配元素的文档

[英]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.所以,基本上,我想找到每个人(文档)在他们最喜欢的 colors 中具有蓝色或栗色。

Use the $in operator to filter a range of values.使用$in运算符过滤一系列值。

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您可以在此处找到更多文档https://docs.mongodb.com/manual/reference/operator/query/in/#use-the-in-operator-to-match-values-in-an-array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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