มาสร้างคอลเล็กชันพร้อมเอกสารที่มีข้อมูลเซิร์ฟเวอร์กันเถอะ
> db.demo707.insertOne(
{
id:101,
"serverInformation":
[
{
"IP":"192.56.34.3",
"Status":"Active"
},
{
"IP":"192.56.36.4",
"Status":"Inactive"
}
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6f852551299a9f98c93c8") }
แสดงเอกสารทั้งหมดด้วยเมธอด find()
> db.demo707.find();
ผลลัพธ์ที่ได้
{ "_id" : ObjectId("5ea6f852551299a9f98c93c8"), "id" : 101, "serverInformation" : [ { "IP" : "192.56.34.3", "Status" : "Active" }, { "IP" : "192.56.36.4", "Status" : "Inactive" } ] }
คำสั่งอัปเดตสถานะเซิร์ฟเวอร์จาก Active เป็น Inactive
>db.demo707.update({"serverInformation.IP":"192.56.34.3"},{$set:{"serverInformation.$.Status":"Inactive"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
แสดงเอกสารทั้งหมดอีกครั้ง
> db.demo707.find();
ผลลัพธ์หลังอัปเดต
{ "_id" : ObjectId("5ea6f852551299a9f98c93c8"), "id" : 101, "serverInformation" : [ { "IP" : "192.56.34.3", "Status" : "Inactive" }, { "IP" : "192.56.36.4", "Status" : "Inactive" } ] }