คุณสามารถใช้ฟังก์ชัน update() เพื่อแทรกระเบียนใน MongoDB หากไม่มีอยู่ เพื่อให้เข้าใจแนวคิด ให้เราสร้างคอลเลกชันพร้อมกับเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.insertIfNotExistsDemo.insertOne({"StudentName":"Mike","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7eec7b559dd2396bcfbfc2")
}
> db.insertIfNotExistsDemo.insertOne({"StudentName":"Sam","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7eec97559dd2396bcfbfc3")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังต่อไปนี้ −
> db.insertIfNotExistsDemo.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"),
"StudentName" : "Mike",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c7eec97559dd2396bcfbfc3"),
"StudentName" : "Sam",
"StudentAge" : 22
} นี่คือแบบสอบถามเพื่อแทรกบันทึกหากไม่มีอยู่แล้ว -
> key = {"StudentName":"David"}
{ "StudentName" : "David" }
> value = {"StudentName":"David","StudentAge":26}
{ "StudentName" : "David", "StudentAge" : 26 }
> db.insertIfNotExistsDemo.update(key, value, upsert=true); ต่อไปนี้เป็นผลลัพธ์ -
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5c7eecd4c743760e97af8261")
}) ให้เราตรวจสอบเอกสารทั้งหมดจากคอลเลกชัน แบบสอบถามมีดังต่อไปนี้ −
> db.insertIfNotExistsDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"),
"StudentName" : "Mike",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c7eec97559dd2396bcfbfc3"),
"StudentName" : "Sam",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c7eecd4c743760e97af8261"),
"StudentName" : "David",
"StudentAge" : 26
} ดูผลลัพธ์ตัวอย่าง แทรก “StudentName”:”David” และ “StudentAge”:26 สำเร็จแล้ว