Articles → MONGODB → Upsert In Mongodb

Upsert In Mongodb






Purpose





Syntax


db.collection.update(
   <query>,
   <update>,
   {
     upsert: true
   }
)



Example




Picture showing the sample mongodb collection




db.mycollection.updateOne({ name: 'John Doe' },  { $set: { age: 70 } }, { upsert: true })


Picture showing executing the updateOne with upsert true




Picture showing updating the value of the age field




db.mycollection.updateOne({ name: 'John Doe1' },  { $set: { age: 70 } }, { upsert: true })




Picture showing executing the updateOne with upsert true




Picture showing the collection after inserting a document



Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 27, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250