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

Update ฟิลด์ MongoDB ด้วยค่าจากอีกฟิลด์หนึ่ง (Aggregation)

ใช้ Aggregation Pipeline ร่วม $addFields และ $out เพื่ออัปเดตฟิลด์โดยใช้ค่าจากฟิลด์อื่น

สร้างคอลเล็กชัน name


> db.name.insert({"FirstName":"John","LastName":"Smith"});
WriteResult({ "nInserted" : 1 })
> db.name.find().pretty();
{ "_id" : ObjectId("5c6c00dd68174aae23f5ef55"), "FirstName" : "John", "LastName" : "Smith" }

สร้างคอลเล็กชัน studentInformation


> db.studentInformation.insert({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
WriteResult({ "nInserted" : 1 })
> db.studentInformation.find().pretty();
{ "_id" : ObjectId("5c6c013068174aae23f5ef56"), "StudentFirstName" : "Carol", "StudentLastName" : "Taylor" }

อัปเดตคอลเล็กชัน name ด้วยข้อมูลจาก studentInformation


> db.studentInformation.aggregate([
    { $addFields: { "FullName": { $concat: ["$StudentFirstName", " ", "$StudentLastName"] }}},
    { $out: "name" }
]);

ตรวจสอบคอลเล็กชัน name หลังอัปเดต


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

{
    "_id" : ObjectId("5c6c013068174aae23f5ef56"),
    "StudentFirstName" : "Carol",
    "StudentLastName" : "Taylor",
    "FullName" : "Carol Taylor"
}

Pipeline: $addFields สร้างฟิลด์ใหม่ FullName โดย concat ชื่อ-นามสกุล → $out เขียนทับคอลเล็กชัน name (แทนที่ข้อมูลเดิมทั้งหมด)

คำเตือน: $out จะแทนที่คอลเล็กชันปลายทางทั้งหมด ใช้ด้วยความระมัดระวัง