Mongo查找文档,其中数组包含给定数组的x值 [英] Mongo find documents where array contains x values of given array

查看:89
本文介绍了Mongo查找文档,其中数组包含给定数组的x值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个收藏,里面有类似的文件.在每个文档中未设置实体字段,并且该字段具有不同的值:

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"
    ]
}

现在,我想查找所有包含给定数组的x个值的文档:["Entity1","Entity2","Entity3","Entity4"]

Now I want to find all documents which contains exactly x values of the given array : ["Entity1","Entity2","Entity3","Entity4"]

对于上面发布的文档,值Entity1,Entity2,Entity4匹配:

For the document posted above the values Entity1, Entity2, Entity4 are matching:

  • x = 4不应找到该文档(3个匹配值,但x为4)
  • x = 3个文档(3个匹配-> size = x)
  • x = 2不应找到该文档(3个匹配值,但x为2)
  • x = 1找不到文档(3个匹配值,但x为1)

推荐答案

您可以为此使用聚合.这可能是您要寻找的:

You can use aggregation for this. This is probably what you're looking for:

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

这篇关于Mongo查找文档,其中数组包含给定数组的x值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆