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

คิวรี่ MongoDB แทนที่ค่าด้วย Aggregate Framework

ใช้ Aggregate Framework พร้อม $literal เพื่อแทนที่ค่าฟิลด์ในผลลัพธ์ (ไม่เปลี่ยนข้อมูลจริงในฐานข้อมูล) เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.replaceValueDemo.insertOne(
  {
    _id : 100,
    "EmployeeName" :"Chris",
    "EmployeeOtherDetails": {
      "EmployeeDesignation" : "HR",
      "EmployeeAge":27
    }
  }
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.replaceValueDemo.insertOne(
  {
    _id : 101,
    "EmployeeName" :"David",
    "EmployeeOtherDetails": {
      "EmployeeDesignation" : "Tester",
      "EmployeeAge":26
    }
  }
);
{ "acknowledged" : true, "insertedId" : 101 }

แสดงเอกสาร:

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

คิวรี่ Aggregate แทนที่ EmployeeDesignation เป็น "Developer" ในผลลัพธ์:

> db.replaceValueDemo.aggregate([{
  "$project": {
    "_id": 1,
    "EmployeeOtherDetails": {
      "EmployeeAge": 1,
      "EmployeeDesignation" : { $literal: "Developer" }
    }
  }
}]);

คำอธิบาย: $literal ใช้ระบุค่าคงที่ใน pipeline โดยไม่ต้องอ้างอิงจากฟิลด์ใดๆ เหมาะสำหรับการสร้างฟิลด์ใหม่หรือแทนที่ค่าในขั้นตอน $project โดยไม่กระทบข้อมูลต้นทาง