如何在 MongoDB 中對單個集合中的文件之間的集進行交集運算?


你可以為此使用 $setIntersection。我們首先用文件建立一個集合 -

> db.setInterSectionDemo.insertOne(
...    {"_id":101, "Value1":[55,67,89]}
... );
{ "acknowledged" : true, "insertedId" : 101 }
> db.setInterSectionDemo.insertOne(
...    {"_id":102, "Value2":[90,45,55]}
... );
{ "acknowledged" : true, "insertedId" : 102 }
> db.setInterSectionDemo.insertOne(
...    {"_id":103, "Value3":[92,67,45]}
... );
{ "acknowledged" : true, "insertedId" : 103 }

以下是使用 find() 方法從集合中顯示所有文件的查詢 -

> db.setInterSectionDemo.find().pretty();

這會產生以下輸出 -

{ "_id" : 101, "Value1" : [ 55, 67, 89 ] }
{ "_id" : 102, "Value2" : [ 90, 45, 55 ] }
{ "_id" : 103, "Value3" : [ 92, 67, 45 ]

以下是查詢 MongoDB 中單個集合中文件之間集交集的查詢 -

> db.setInterSectionDemo.aggregate([
...    {
...       "$match": {
...          "_id": { "$in": [101, 103] }
...       }
...    },
...    {
...       "$group": {
...          "_id": 0,
...          "firstValue": { "$first": "$Value1" },
...          "secondValue": { "$last": "$Value3" }
...       }
...    },
...    {
...       "$project": {
...          "firstValue": 1,
...          "secondValue": 1,
...          "CommonValue": { "$setIntersection": [ "$firstValue", "$secondValue" ] },
...          "_id": 0
...       }
...    }
... ]);

這會產生以下輸出 -

{ "firstValue" : [ 55, 67, 89 ], "secondValue" : [ 92, 67, 45 ], "CommonValue" : [ 67 ] }

更新於: 2019 年 7 月 30 日

114 次瀏覽

開啟你的 事業

完成課程獲取認證

開始學習
廣告