Dùng $setIntersection trong aggregation. Tạo collection:
> 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 }
Hiển thị tất cả:
> db.setInterSectionDemo.find().pretty();
Kết quả:
Tìm giao của Value1 (id=101) và Value3 (id=103):
> 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 } } ]);Kết quả (phần tử chung: 67):