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

แปลงฟิลด์เป็นอาร์เรย์ด้วยออปเปอเรชัน Update ใน MongoDB

เพื่อแปลงฟิลด์ทั่วไปให้กลายเป็นอาร์เรย์ สามารถใช้คำสั่ง update() ภายใน forEach() ได้ ให้สร้างคอลเลกชันตัวอย่าง:

> db.demo18.insertOne({"StudentName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e1387fc55d0fc6657d21f0e") }

แสดงข้อมูลก่อนการเปลี่ยนแปลง:

> db.demo18.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e1387fc55d0fc6657d21f0e"), "StudentName" : "John" }

คิวรีแปลงฟิลด์ StudentName จาก string เป็น array:

> db.demo18.find().forEach(function(myDocument) {
  db.demo18.update(
    { _id: myDocument._id },
    { "$set": { "StudentName": [myDocument.StudentName] } }
  );
})

ตรวจสอบผลลัพธ์:

> db.demo18.find();

ตอนนี้ StudentName กลายเป็นอาร์เรย์แล้ว:

{ "_id" : ObjectId("5e1387fc55d0fc6657d21f0e"), "StudentName" : [ "John" ] }

ข้อสังเกต

  • วิธีนี้เหมาะสำหรับการ migrate ข้อมูลเดิม (data migration)
  • ใช้ $set เพื่อกำหนดค่าใหม่แทนที่ค่าเดิม
  • ใน MongoDB เวอร์ชันใหม่แนะนำให้ใช้ updateMany() พร้อม pipeline แทน forEach เพื่อประสิทธิภาพที่ดีกว่า