ใช้ save() บันทึกออบเจ็กต์จากตัวแปร JavaScript แล้วตัวแปรจะถูกอัปเดต _id อัตโนมัติ
สร้างตัวแปรออบเจ็กต์
> var studentDetails={"StudentFirstName":"Chris","StudentLastName":"Brown","StudentAge":24};
บันทึกด้วย save()
> db.demo45.save(studentDetails);
WriteResult({ "nInserted" : 1 })
แสดงตัวแปรหลังบันทึก (มี _id เพิ่มเข้ามา)
> studentDetails;
{
"StudentFirstName" : "Chris",
"StudentLastName" : "Brown",
"StudentAge" : 24,
"_id" : ObjectId("5e25dab4cfb11e5c34d898ec")
}
สรุป: save() ทำงานแบบ upsert - ถ้าตัวแปรมี __id อยู่แล้วจะ update, ถ้าไม่มีจะ insert ใหม่และเติม _id กลับเข้าไปในตัวแปรเดิม ทำให้อ้างอิงเอกสารที่เพิ่งสร้างได้ทันที