且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MongoDB中的单个集合中找到文档之间的集合的交集?

更新时间:2021-09-04 22:09:14

使用 设置运算符 魔术是 $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"] }
                }
            }
        }
    }
])