Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lấy giá trị duy nhất từ 2 mảng trong một tài liệu MongoDB ($setUnion)

Sử dụng $setUnion trong aggregation để gộp 2 mảng và lấy giá trị duy nhất (union set). Tạo collection:

> db.demo608.insertOne({"ListOfName1":["John","Chris","Bob","David"],"ListOfName2":["Bob","Sam","John","Robert","Chris"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e974542f57d0dc0b182d62b") }

Hiển thị dữ liệu (2 mảng có trùng lặp):

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

Aggregation $project với $setUnion:

> db.demo608.aggregate([ {$project:{SetOfNames:{$setUnion:['$ListOfName1','$ListOfName2']}}} ]).pretty();

Kết quả (6 giá trị duy nhất, đã sắp xếp):


Các toán tử set trong aggregation:

  • $setUnion: Hợp (union) - phần tử xuất hiện ở bất kỳ mảng nào
  • $setIntersection: Giao (intersection) - phần tử xuất hiện ở TẤT CẢ mảng
  • $setDifference: Hiệu (difference) - phần tử ở mảng 1 KHÔNG ở mảng 2
  • $setIsSubset: Kiểm tra mảng 1 có phải tập con mảng 2
  • $setEquals: Kiểm tra 2 mảng có cùng phần tử