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

MongoDB: ตั้งค่า Sub-item ในอาร์เรย์ด้วย Positional Operator $

ใช้ Positional Operator $ เพื่ออัปเดตสมาชิกเฉพาะในอาร์เรย์ที่ตรงกับเงื่อนไขค้นหา สร้างคอลเลกชันตัวอย่าง:

> db.demo22.insertOne({
  ProductId:101,
  ProductDetails: [
    { ProductFirstPrice: '35', ProductSecondPrice: '75' },
    { ProductFirstPrice: '', ProductSecondPrice: '' },
    { ProductFirstPrice: '78', ProductSecondPrice: '24' }
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e14c0b422d07d3b95082e70") }

แสดงข้อมูล:

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

อัปเดต ProductFirstPrice ของสมาชิกแรกที่มีค่า "35" ให้เป็นค่าว่าง:

> db.demo22.update(
  { "ProductDetails.ProductFirstPrice" : "35" },
  { $set : { "ProductDetails.$.ProductFirstPrice" : "" }},
  false, true
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

ผลลัพธ์ (สมาชิกแรกที่ ProductFirstPrice="35" ถูกเปลี่ยนเป็นค่าว่าง):

{ "_id" : ObjectId("5e14c0b422d07d3b95082e70"), "ProductId" : 101, "ProductDetails" : [ { "ProductFirstPrice" : "", "ProductSecondPrice" : "75" }, { "ProductFirstPrice" : "", "ProductSecondPrice" : "" }, { "ProductFirstPrice" : "78", "ProductSecondPrice" : "24" } ] }

การทำงานของ Positional Operator $

  • $ อ้างอิงถึง สมาชิกแรก ในอาร์เรย์ที่ตรงกับเงื่อนไขใน query
  • ใช้ได้กับอาร์เรย์ระดับบนสุด (top-level array) เท่านั้น
  • สำหรับอาร์เรย์ซ้อนหลายระดับ ให้ใช้ $[<identifier>] (filtered positional operator) ใน MongoDB 3.6+
  • พารามิเตอร์ที่ 3,4 ของ update(): upsert, multi (deprecated ในเวอร์ชันใหม่)