If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
पिछले topic में आपने Collection (Table) से documents fetch करना सीखा , इस topic में हम collection में records / documents को update करना सीखेंगे।
MongoDB में documents को update करने के दो तरीके है -
updateOne() : single document update करने के लिए।
updateMany() : multiple document update करने के लिए।
दोनों ही function में 2 arguments pass होते हैं , पहला argument query object होता है जिसके bases पर आप documents / records find करते हो और 2nd argument में Object data होता है जिसे आप update करना चाहते है।
तो जैसे SQL databases में rows को update करने के लिए SET query use करते थे बैसे ही MongoDB में $set operator होता है documents को update करने के लिए।
●●●
updateOne() method , pass की गयी query से match करने वाले पहले record को update करता है।
db.users.updateOne(
{"name" : "Raju"} ,
{"$set" : {"salery" : 10000} }
)अगर record update हुआ तो matching document और modified document की information दिखेगी जैसे नीचे output में दिख रही है।
{
"acknowledged" : true,
"matchedCount" : 1.0,
"modifiedCount" : 1.0
}ध्यान रहे अगर document में field exist नहीं है जो अपने update object में pass किया तो new field add हो जायेगा।
db.users.updateOne( {}, {"$set" : {"address" : "India"} } )●●●
अगर आप चाहते हैं कि अगर दी गयी condition पर records match नहीं करता तो new document create हो जाए तो आप upsert option का use कर सकते हैं।
db.users.updateOne(
{"name" : "New User"} ,
{
"$set" :
{
"name" : "New User",
"age" : 67,
"address" : "Jamaica",
"salery" : 10000
}
},
{"upsert" : true}
)अगर record match हुआ तो update हो जायगा otherwise , newly inserted document की _id मिल जायगी।
{
"acknowledged" : true,
"matchedCount" : 0.0,
"modifiedCount" : 0.0,
"upsertedId" : ObjectId("64f61541c02b99999b01f182")
}●●●
updateMany() method , pass की गयी query से match करने वाले सभी documents/records को update करता है।
db.users.updateMany( {}, {"$set" : {"address" : "India"} } )