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

查看:14
本文介绍了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 个匹配 -> 大小 = x)
  • x = 2 不应该找到文档(3 个匹配值,但 x 为 2)
  • x = 1 不应该找到文档(3 个匹配值,但 x 为 1)

推荐答案

您可以为此使用 .aggregate.这可能是您正在寻找的:

You can use .aggregate for this. 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 } }
]);

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

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