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

อัปเดตเอกสาร MongoDB ด้วย ObjectId เท่านั้น

ใช้ update() ร่วมกับ $set และระบุ _id เป็น ObjectId เพื่ออัปเดตเอกสารเฉพาะรายการ

ตัวอย่างข้อมูลทดสอบ

> db.demo34.insertOne({"StudentFirstName":"Chris","StudentAge":24});
> db.demo34.insertOne({"StudentFirstName":"David","StudentAge":23});
> db.demo34.insertOne({"StudentFirstName":"Bob","StudentAge":20});

แสดงข้อมูลก่อนอัปเดต

> db.demo34.find();
{
    "_id" : ObjectId("5e1758b4cfb11e5c34d898cd"),
    "StudentFirstName" : "Chris", "StudentAge" : 24
}
{
    "_id" : ObjectId("5e1758bdcfb11e5c34d898ce"),
    "StudentFirstName" : "David", "StudentAge" : 23
}
{
    "_id" : ObjectId("5e1758c6cfb11e5c34d898cf"),
    "StudentFirstName" : "Bob", "StudentAge" : 20
}

คำสั่งอัปเดตด้วย ObjectId

> db.demo34.update(
    {_id:ObjectId("5e1758bdcfb11e5c34d898ce")},
    {$set:{"StudentFirstName" : "Mike","StudentAge" : 19}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์หลังอัปเดต

> db.demo34.find();
{
    "_id" : ObjectId("5e1758b4cfb11e5c34d898cd"),
    "StudentFirstName" : "Chris", "StudentAge" : 24
}
{
    "_id" : ObjectId("5e1758bdcfb11e5c34d898ce"),
    "StudentFirstName" : "Mike", "StudentAge" : 19
}
{
    "_id" : ObjectId("5e1758c6cfb11e5c34d898cf"),
    "StudentFirstName" : "Bob", "StudentAge" : 20
}

สรุป: ระบุ _id ด้วย ObjectId ในเงื่อนไขค้นหา (query) แล้วใช้ $set ระบุฟิลด์และค่าใหม่