คุณสามารถใช้ upsert เช่นเมื่อใดก็ตามที่คุณแทรกค่าและมีอยู่แล้ว การอัปเดตจะดำเนินการ หากไม่มีค่าอยู่แล้วก็จะถูกแทรก
ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Larry","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a633815e86fd1496b38a4")
}
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Mike","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a634a15e86fd1496b38a5")
}
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Sam","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a635015e86fd1496b38a6")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : ObjectId("5c9a633815e86fd1496b38a4"),
"StudentName" : "Larry",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9a634a15e86fd1496b38a5"),
"StudentName" : "Mike",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9a635015e86fd1496b38a6"),
"StudentName" : "Sam",
"StudentAge" : 24
} กรณีที่ 1 :ต่อไปนี้เป็นแบบสอบถามเมื่อมีค่าอยู่แล้ว เนื่องจากค่าที่คุณกำลังแทรกมีอยู่แล้ว ค่านั้นจะได้รับการอัปเดต
> db.onlyInsertIfValueIsUniqueDemo.update({StudentName:"Mike"},{$set:{"StudentAge":27}},{ upsert: true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) ดูเอกสารทั้งหมดอีกครั้ง ต่อไปนี้เป็นแบบสอบถาม
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : ObjectId("5c9a633815e86fd1496b38a4"),
"StudentName" : "Larry",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9a634a15e86fd1496b38a5"),
"StudentName" : "Mike",
"StudentAge" : 27
}
{
"_id" : ObjectId("5c9a635015e86fd1496b38a6"),
"StudentName" : "Sam",
"StudentAge" : 24
} กรณีที่ 2 :ต่อไปนี้เป็นแบบสอบถามเมื่อค่าไม่ซ้ำกัน เนื่องจากค่าที่คุณกำลังแทรกไม่มีอยู่ ค่านั้นจึงถูกแทรก
>db.onlyInsertIfValueIsUniqueDemo.update({StudentName:"David"},{$set:{"StudentAge":25}},{ upsert: true});
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5c9a654ce628c11759caea54")
}) ดูเอกสารทั้งหมดอีกครั้ง ต่อไปนี้เป็นแบบสอบถาม
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : ObjectId("5c9a633815e86fd1496b38a4"),
"StudentName" : "Larry",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9a634a15e86fd1496b38a5"),
"StudentName" : "Mike",
"StudentAge" : 27
}
{
"_id" : ObjectId("5c9a635015e86fd1496b38a6"),
"StudentName" : "Sam",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c9a654ce628c11759caea54"),
"StudentName" : "David",
"StudentAge" : 25
}