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

MongoDB Query เปลี่ยนลำดับ Element ใน Array (Swap)

MongoDB ไม่มี Operator ตรงๆ สำหรับ Swap Element ใน Array แต่สามารถทำได้โดยอ่านเอกสาร มา Swap ใน JavaScript แล้ว Update กลับไป เนื้อหานี้สาธิตการ Swap Element ตำแหน่ง 0 และ 1 ใน Array Name

ตัวอย่างข้อมูลทดสอบ

> db.demo301.insertOne({"Name":["Chris","David","Bob"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4d6ff55d93261e4bc9ea51") }

แสดงข้อมูลเดิม

> db.demo301.find();
{ "_id" : ObjectId("5e4d6ff55d93261e4bc9ea51"), "Name" : [ "Chris", "David", "Bob" ] }

Query Swap Element (ใช้ forEach ใน Shell)

> db.demo301.find({}, { Name : 1 }).forEach(function(n) {
  var t = n.Name[0];
  n.Name[0] = n.Name[1];
  n.Name[1] = t;
  db.demo301.update({ _id: n._id }, { $set: { Name: n.Name } });
})

ผลลัพธ์หลัง Swap

> db.demo301.find();
{ "_id" : ObjectId("5e4d6ff55d93261e4bc9ea51"), "Name" : [ "David", "Chris", "Bob" ] }

วิธีทางเลือก (MongoDB 4.2+ ใช้ Aggregation Pipeline ใน Update)

> db.demo301.updateMany(
  {},
  [{ $set: { Name: { $concatArrays: [
    [ { $arrayElemAt: ["$Name", 1] } ],
    [ { $arrayElemAt: ["$Name", 0] } ],
    { $slice: ["$Name", 2, { $size: "$Name" }] }
  ] } }]
);

คำอธิบาย

  • วิธี forEach: อ่านทีละ Doc, Swap ใน Memory, Update กลับ - เหมาะสำหรับข้อมูลน้อย/One-time
  • วิธี Aggregation Pipeline (4.2+): Atomic, รวดเร็วกว่า, รองรับ Bulk Update
  • $arrayElemAt ดึง Element ตาม Index, $slice ตัด Array, $concatArrays รวม Array
  • สำหรับ Swap หลายตำแหน่ง ควรเขียน Function/Script แทน