มาสร้างคอลเล็กชันพร้อมเอกสารกันเถอะ
> db.demo595.insertOne( { "Information": [
{ "_id": new ObjectId(), Name:"Chris" },
{ _id:new ObjectId(), Name:"Robert" } ] } );
{ "acknowledged" : true, "insertedId" : ObjectId("5e93369cfd2d90c177b5bce4") }
แสดงเอกสารทั้งหมดด้วยเมธอด find()
> db.demo595.find().pretty();
ผลลัพธ์ที่ได้
{ "_id" : ObjectId("5e93369cfd2d90c177b5bce4"), "Information" : [ { "_id" : ObjectId("5e93369cfd2d90c177b5bce2"), "Name" : "Chris" }, { "_id" : ObjectId("5e93369cfd2d90c177b5bce3"), "Name" : "Robert" } ] }
คำสั่งอัปเดตเอกสารซ้อน (เปลี่ยน Name Chris เป็น David Miller)
>db.demo595.update({"Information._id":ObjectId("5e93369cfd2d90c177b5bce2")}, {$set:{"Information.$.Name":"David Miller"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
แสดงเอกสารทั้งหมดหลังอัปเดต
> db.demo595.find().pretty();
ผลลัพธ์ที่ได้
{ "_id" : ObjectId("5e93369cfd2d90c177b5bce4"), "Information" : [ { "_id" : ObjectId("5e93369cfd2d90c177b5bce2"), "Name" : "David Miller" }, { "_id" : ObjectId("5e93369cfd2d90c177b5bce3"), "Name" : "Robert" } ] }