在Mongo中,我如何将所有收集项与较大的数组相匹配? [英] In Mongo, how would I match all items of collection against a larger array?

查看:93
本文介绍了在Mongo中,我如何将所有收集项与较大的数组相匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个集合中有3个项目:

Let's say I have 3 items in a collection:

[
    {
        id: 'a',
        items: [1, 2, 3]
    }, {
        id: 'b',
        items: [4, 5, 6]
    }, {
        id: 'c',
        items: [7, 8, 9]
    }
]

在JavaScript代码方面,我所拥有的只是一个数组 [5,2,6,4,7,8] 。我如何编写查询以仅从集合中选择第二个对象,因为我的数组包含其项目数组的所有元素(4,5和6)?

On the JavaScript code side, all I have is an array [5, 2, 6, 4, 7, 8]. How would I compose my query to select only the 2nd object from the collection since my array has all the elements (4, 5 and 6) of its items array?

推荐答案

使用mongoDB 聚合集合运算符 您可以过滤数组。首先找出给定数组与实际数据库数组的交集,然后使用set equals方法。检查以下查询:

Using mongoDB Aggregation Set Operator you can filter your array. First find out intersection of given array with actual database array and after that used set equals method. check below query :

db.collectionName.aggregate({
    "$project": {
    "checkAllElem": {
        "$setEquals": [{
            "$setIntersection": ["$items", [5, 2, 6, 4, 7, 8]]
        }, "$items"]
    },
    "items": 1
    }
}, {
    "$match": {
    "checkAllElem": true
    }
})

这篇关于在Mongo中,我如何将所有收集项与较大的数组相匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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