[英]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.