MongoDB Update Records In Hindi | Update Documents In MongoDB In Hindi

📔 : MongoDB 🔗

पिछले 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 करना चाहते है।

MongoDB $set Operator

तो जैसे SQL databases में rows को update करने के लिए SET query use करते थे बैसे ही MongoDB में $set operator होता है documents को update करने के लिए।

MognoDB updateOne() Example

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"} } )

MongoDB Insert if not found

अगर आप चाहते हैं कि अगर दी गयी 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")
}

MongoDB updateMany() Example

updateMany() method , pass की गयी query से match करने वाले सभी documents/records को update करता है।

db.users.updateMany( {}, {"$set" : {"address" : "India"} } )

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers