सशर्त अप्सर्ट या अपडेट के लिए, आप $max ऑपरेटर का उपयोग कर सकते हैं। आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं
>db.conditionalUpdatesDemo.insertOne({"_id":100,"StudentFirstScore":89,"StudentSecondScore":78,"BiggestScore":89});
{ "acknowledged" : true, "insertedId" : 100 }
>db.conditionalUpdatesDemo.insertOne({"_id":101,"StudentFirstScore":305,"StudentSecondScore":560,"BiggestScore":1050});
{ "acknowledged" : true, "insertedId" : 101 }
>db.conditionalUpdatesDemo.insertOne({"_id":103,"StudentFirstScore":560,"StudentSecondScore":789,"BiggestScore":880});
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from a collection with the help of find() method:
> db.conditionalUpdatesDemo.find().pretty(); यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : 100,
"StudentFirstScore" : 89,
"StudentSecondScore" : 78,
"BiggestScore" : 89
}
{
"_id" : 101,
"StudentFirstScore" : 305,
"StudentSecondScore" : 560,
"BiggestScore" : 1050
}
{
"_id" : 103,
"StudentFirstScore" : 560,
"StudentSecondScore" : 789,
"BiggestScore" : 880
} MongoDB में सशर्त अप्सर्ट या अपडेट के लिए क्वेरी निम्नलिखित है
> db.conditionalUpdatesDemo.update( { _id: 100 }, { $max: { "BiggestScore": 150 } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) आइए देखें कि "बिगस्टस्कोर" फ़ील्ड को _id 100 के लिए 150 मान के साथ अपडेट किया गया है या नहीं
> db.conditionalUpdatesDemo.find().pretty();
यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : 100,
"StudentFirstScore" : 89,
"StudentSecondScore" : 78,
"BiggestScore" : 150
}
{
"_id" : 101,
"StudentFirstScore" : 305,
"StudentSecondScore" : 560,
"BiggestScore" : 1050
}
{
"_id" : 103,
"StudentFirstScore" : 560,
"StudentSecondScore" : 789,
"BiggestScore" : 880
}