आप अप्सर्ट का उपयोग कर सकते हैं यानी जब भी आप कोई मान डालते हैं और यह पहले से मौजूद है तो अपडेट किया जाएगा। यदि मान पहले से मौजूद नहीं है तो इसे डाला जाएगा।
आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं
> 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")
} खोज () विधि की मदद से संग्रह से सभी दस्तावेजों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है
> 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
}