如何在 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 ] }
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP