Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

รวม Array สองฟิลด์ใน MongoDB ด้วย $setUnion (Union Arrays)

บทความนี้สาธิตการใช้ $setUnion ใน Aggregation Pipeline เพื่อรวม (Merge) Array สองฟิลด์ให้กลายเป็น Array เดียวที่มีค่าไม่ซ้ำกัน (Unique Values)

สร้างข้อมูลตัวอย่าง

> db.mergeTwoArrayFieldDemo.insertOne({"NaturalNumbers":[1,2,3,8,10,20,30],"WholeNumbers":[0,1,2,63,78,20,45]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd68e4057806ebf1256f11d") }

แสดงข้อมูลต้นฉบับ

> db.mergeTwoArrayFieldDemo.find().pretty();
{
  "_id" : ObjectId("5cd68e4057806ebf1256f11d"),
  "NaturalNumbers" : [ 1, 2, 3, 8, 10, 20, 30 ],
  "WholeNumbers" : [ 0, 1, 2, 63, 78, 20, 45 ]
}

รวม Array ทั้งสองด้วย $setUnion

> db.mergeTwoArrayFieldDemo.aggregate([
  { "$project": {
    "MergedArray": { "$setUnion": [ "$NaturalNumbers", "$WholeNumbers" ] }
  }}
]);

ผลลัพธ์ (เรียงจากน้อยไปมาก อัตโนมัติ)

{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "MergedArray" : [ 0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78 ] }

คำอธิบาย $setUnion

  • รับ Array 2 ตัวขึ้นไป เป็น Argument
  • คืนค่า Array ที่รวมค่า ไม่ซ้ำกัน (Set Union)
  • ผลลัพธ์ถูก เรียงลำดับอัตโนมัติ (Ascending)
  • ทำงานกับ Primitive Values (Number, String, Boolean)

Array Set Operators อื่นๆ ใน Aggregation

ตัวอย่าง: $setIntersection (หาค่าที่ซ้ำกัน)

db.collection.aggregate([
  { $project: {
    commonNumbers: { $setIntersection: ["$NaturalNumbers", "$WholeNumbers"] }
  }}
]);
// ผลลัพธ์: [1, 2, 20]

ตัวอย่าง: $setDifference (หาค่าที่ต่างกัน)

db.collection.aggregate([
  { $project: {
    onlyInNatural: { $setDifference: ["$NaturalNumbers", "$WholeNumbers"] },
    onlyInWhole: { $setDifference: ["$WholeNumbers", "$NaturalNumbers"] }
  }}
]);
Operatorคำอธิบายตัวอย่างผลลัพธ์
$setUnionรวมทั้งหมด ไม่ซ้ำ (Union)[1,2] U [2,3] = [1,2,3]
$setIntersectionค่าที่มีในทุก Array (Intersection)[1,2] ∩ [2,3] = [2]
$setDifferenceค่าใน Array แรก แต่ไม่ใน Array ที่สอง[1,2] - [2,3] = [1]
$setIsSubsetเช็คว่า Array แรกเป็น Subset ของ Array ที่สอง[1,2] ⊆ [1,2,3] = true
$setEqualsเช็คว่า Array ทั้งสองมีค่าเท่ากันหมด (ไม่สนใจ Order)[1,2] = [2,1] = true