如何在MongoDB中的单个集合中找到文档之间的集合的交集? [英] How to find set intersection of sets between the documents in a single collection in MongoDB?
问题描述
下面的名为"coll"的集合在mongodb中维护.
The below collection named "coll" was maintained in the mongodb.
{
{"_id":1, "set":[1,2,3,4,5]},
{"_id":2, "set":[0,2,6,4,5]},
{"_id":3, "set":[1,2,5,10,22]}
}
如何在上述收集文档中找到集合元素与_id的1和3的交集.
How to find the intersection of the set elements in the above collection documents with _id's 1 and 3.
推荐答案
使用 设置运算符 魔术是 $setIntersection
.
以下聚合管道可以实现您所追求的目标:
The following aggregation pipeline achieves what you are after:
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
}
}
])
输出:
/* 0 */
{
"result" : [
{
"set1" : [1,2,3,4,5],
"set2" : [1,2,5,10,22],
"commonToBoth" : [1,2,5]
}
],
"ok" : 1
}
更新
要相交三个或更多文档,您需要 $reduce
运算符以展平数组.这将使您可以与任意数量的数组相交,因此,这不仅适用于文档1和3中两个数组的相交,而且还适用于多个数组.
UPDATE
For three or more documents to be intersected, you'd need the $reduce
operator to flatten the arrays. This will allow you to intersect any number of arrays, so instead of just doing an intersection of the two arrays from docs 1 and 3, this will apply to multiple arrays as well.
考虑运行以下聚合操作:
Consider running the following aggregate operation:
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"] }
}
}
}
}
])
这篇关于如何在MongoDB中的单个集合中找到文档之间的集合的交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!