使用
聚合框架来获得所需结果。实现这一魔法的聚合
集合运算符是
$setIntersection
。
以下聚合管道实现了您想要的结果:
db.test.aggregate([
{
"$match": {
"_id": { "$in": [1, 3] }
}
},
{
"$group": {
"_id": 0,
"set1": { "$first": "$set" },
"set2": { "$last": "$set" }
}
},
{
"$project": {
"set1": 1,
"set2": 1,
"commonToBoth": { "$setIntersection": [ "$set1", "$set2" ] },
"_id": 0
}
}
])
输出:
{
"result" : [
{
"set1" : [1,2,3,4,5],
"set2" : [1,2,5,10,22],
"commonToBoth" : [1,2,5]
}
],
"ok" : 1
}
更新
如果要相交三个或更多文档,则需要使用$reduce
操作符来展平数组。这将允许你相交任意数量的数组,因此不仅可以对来自文档1和3的两个数组进行相交,还可以应用于多个数组。
考虑运行以下聚合操作:
db.test.aggregate([
{ "$match": { "_id": { "$in": [1, 3] } } },
{
"$group": {
"_id": 0,
"sets": { "$push": "$set" },
"initialSet": { "$first": "$set" }
}
},
{
"$project": {
"commonSets": {
"$reduce": {
"input": "$sets",
"initialValue": "$initialSet",
"in": { "$setIntersection": ["$$value", "$$this"] }
}
}
}
}
])
BufBuilder attempted to grow() to 67108870 bytes, past the 64MB limit.
的错误提示:每个集合可能包含约600K个7字节元素。您有什么解决方案或变通方法吗?提前感谢您! - mspapant