ใช้ $setOnInsert ใน Upsert
โอเปอเรเตอร์ $setOnInsert ตั้งค่าฟิลด์เฉพาะเมื่อมีการ insert ใหม่ (upsert: true) ไม่ต้องทำเมื่อ update existing document
ตัวอย่าง
สร้างคอลเลกชัน addCurrentDateTimeDemo มีข้อมูลเดิม:
> db.addCurrentDateTimeDemo.insertOne({"StudentName":"John","StudentAdmissionDate":new Date("2012-01-21")});
> db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2013-05-24")});
> db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2019-07-26")});
Upsert ใหม่พร้อมตั้งค่าเวลาปัจจุบัน
> db.addCurrentDateTimeDemo.update(
{_id: 1},
{
$set: {StudentName: "Robert"},
$setOnInsert: {StudentAdmissiondate: new Date()}
},
{upsert: true}
);
ผลลัพธ์:
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
ตรวจสอบข้อมูล
> db.addCurrentDateTimeDemo.find().pretty();
ผลลัพธ์ (มีเอกสารใหม่ _id: 1):
{ "_id" : 1, "StudentAdmissiondate" : ISODate("2019-03-24T16:21:21.269Z"), "StudentName" : "Robert" }
$setOnInsert เหมาะสำหรับฟิลด์ createdAt ที่ต้องการตั้งค่าเฉพาะตอนสร้างใหม่