繁体   English   中英

在Mongo中,我如何将集合的所有项目与更大的阵列匹配?

[英]In Mongo, how would I match all items of collection against a larger array?

假设我有3个收藏品:

[
    {
        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] 由于我的数组具有其items数组的所有元素(4、5和6),我该如何构成查询以仅从集合中选择第二个对象?

使用mongoDB Aggregation Set Operator,您可以过滤阵列。 首先找出给定数组与实际数据库数组的交集,然后使用set equals方法。 检查以下查询:

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

暂无
暂无

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

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