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

การเพิ่มฟิลด์ใหม่ให้ทุกเอกสารในคอลเลกชันขนาดใหญ่ของ MongoDB

เมื่อต้องการเพิ่มฟิลด์ใหม่ให้กับทุกเอกสารในคอลเลกชันขนาดใหญ่ สามารถใช้ find().forEach() ร่วมกับ update() หรือ updateOne() เพื่อประมวลผลทีละเอกสาร

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

> db.addingNewPropertyDemo.insertOne({"StudentName": "John", "StudentAge": 23, "CountryName": "US"});
{ "acknowledged": true, "insertedId": ObjectId("5ca1e61866324ffac2a7dc56") }
> db.addingNewPropertyDemo.insertOne({"StudentName": "David", "StudentAge": 21, "CountryName": "AUS"});
{ "acknowledged": true, "insertedId": ObjectId("5ca1e62366324ffac2a7dc57") }
> db.addingNewPropertyDemo.insertOne({"StudentName": "Bob", "StudentAge": 21, "CountryName": "UK"});
{ "acknowledged": true, "insertedId": ObjectId("5ca1e62d66324ffac2a7dc58") }

แสดงข้อมูลก่อนเพิ่มฟิลด์

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

ผลลัพธ์

{
  "_id": ObjectId("5ca1e61866324ffac2a7dc56"),
  "StudentName": "John",
  "StudentAge": 23,
  "CountryName": "US"
}
{
  "_id": ObjectId("5ca1e62366324ffac2a7dc57"),
  "StudentName": "David",
  "StudentAge": 21,
  "CountryName": "AUS"
}
{
  "_id": ObjectId("5ca1e62d66324ffac2a7dc58"),
  "StudentName": "Bob",
  "StudentAge": 21,
  "CountryName": "UK"
}

เพิ่มฟิลด์ใหม่ StudentNameInUpperCase ให้ทุกเอกสาร

> db.addingNewPropertyDemo.find().forEach(function(data) {
    db.addingNewPropertyDemo.update(
      { _id: data._id },
      { $set: { StudentNameInUpperCase: data.StudentName.toUpperCase() } }
    );
  });

ตรวจสอบหลังเพิ่มฟิลด์

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

ผลลัพธ์ (มีฟิลด์ใหม่ StudentNameInUpperCase)

{
  "_id": ObjectId("5ca1e61866324ffac2a7dc56"),
  "StudentName": "John",
  "StudentAge": 23,
  "CountryName": "US",
  "StudentNameInUpperCase": "JOHN"
}
{
  "_id": ObjectId("5ca1e62366324ffac2a7dc57"),
  "StudentName": "David",
  "StudentAge": 21,
  "CountryName": "AUS",
  "StudentNameInUpperCase": "DAVID"
}
{
  "_id": ObjectId("5ca1e62d66324ffac2a7dc58"),
  "StudentName": "Bob",
  "StudentAge": 21,
  "CountryName": "UK",
  "StudentNameInUpperCase": "BOB"
}

แนะนำสำหรับคอลเลกชันขนาดใหญ่: ใช้ updateMany() ร่วมกับ aggregation pipeline (MongoDB 4.2+) หรือ bulkWrite() เพื่อประสิทธิภาพที่ดีกว่าการวนลูป forEach