Upsert ऑप्शन का उपयोग करना
upsert: true ऑप्शन के साथ update() (या updateOne()/updateMany()) का उपयोग करने से: यदि दस्तावेज़ मौजूद है तो अपडेट होता है, अन्यथा नया दस्तावेज़ डाला जाता है।
उदाहरण: प्रारंभिक डेटा
> 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") }
केस 1: मौजूदा मान अपडेट करना (Mike की उम्र 27 करना)
> db.onlyInsertIfValueIsUniqueDemo.update(
{StudentName: "Mike"},
{$set: {"StudentAge": 27}},
{upsert: true}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
मौजूदा दस्तावेज़ अपडेट होता है (nUpserted: 0, nModified: 1)।
केस 2: नया अद्वितीय मान डालना (David जोड़ना)
> db.onlyInsertIfValueIsUniqueDemo.update(
{StudentName: "David"},
{$set: {"StudentAge": 25}},
{upsert: true}
);
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("...") })
नया दस्तावेज़ डाला जाता है (nUpserted: 1, नया _id उत्पन्न)।
अंतिम डेटा देखना
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
सभी चार दस्तावेज़ दिखाता है जिनमें Mike की उम्र अपडेटेड और David नया है।
महत्वपूर्ण: Upsert के लिए क्वेरी फ़ील्ड (यहां StudentName) पर यूनिक इंडेक्स होने की सिफारिश की जाती है ताकि रेस कंडीशन में डुप्लिकेट न बने। updateOne() के साथ upsert: true आधुनिक पसंदीदा सिंटैक्स है।