简体   繁体   English

Mongo 查找数组包含给定数组的 x 值的文档

[英]Mongo find documents where array contains x values of given array

I have a collection which has documents like that one.我有一个集合,里面有这样的文件。 The entity field is not set in each document and has different values:每个文档中都没有设置实体字段,并且具有不同的值:

{
    "_id" : ObjectId("5388cfbdec82ba7cd5438635"),
    "name" : "Name1",
    "entity" : [ 
        "Entity1", 
        "Entity2", 
        "Entity4",
        "Entity5"
    ]
}

Now I want to find all documents which contains exactly x values of the given array : ["Entity1","Entity2","Entity3","Entity4"]现在我想找到包含给定数组的 x 值的所有文档: ["Entity1","Entity2","Entity3","Entity4"]

Expected result预期结果

For the document posted above the values Entity1, Entity2, Entity4 are matching:对于上面发布的文档,Entity1、Entity2、Entity4 的值是匹配的:

  • x = 4 the document should not be found (3 matching values but x is 4) x = 4 不应该找到文档(3 个匹配值但 x 是 4)
  • x = 3 document should be found (3 matching -> size = x)应该找到 x = 3 个文档(3 个匹配 -> 大小 = x)
  • x = 2 the document should not be found (3 matching values but x is 2) x = 2 不应该找到文档(3 个匹配值但 x 为 2)
  • x = 1 the document should not be found (3 matching values but x is 1) x = 1 不应该找到文档(3 个匹配值但 x 为 1)

You can use .aggregate for this.您可以为此使用.aggregate This is probably what you're looking for:这可能是你正在寻找的:

var y = ["Entity1", "Entity2", "Entity3", "Entity4"];
db.col.aggregate([
    {
        $project :
        {
            _id : 1,
            name : 1,
            entity : 1,
            x : {
                $size : {
                    $ifNull: [{$setIntersection : ["$entity", y]}, []]
                }
            }
        } 
    },
    { $match : { x : 3 } }
]);

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

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