Conditional upsert (multiple insert) when updating document in MongoDB?


For multiple write operations, use bulkWrite() in MongoDB. Let us create a collection with documents −

> db.demo428.insertOne({ "Name" : "Chris", "Age" : 21 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f428bbc41e36cc3cae83")
}
> db.demo428.insertOne({ "Name" : "Chris", "Age" : 23 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f429bbc41e36cc3cae84")
}
> db.demo428.insertOne({ "Name" : "David", "Age" : 22 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f42abbc41e36cc3cae85")
}
> db.demo428.insertOne({ "Name" : "David", "Age" : 21 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f42abbc41e36cc3cae86")
}

Display all documents from a collection with the help of find() method

> db.demo428.find();

This will produce the following output −

{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 }

Following is the query for conditional upsert (insert) when updating document in MongoDB −

> db.demo428.bulkWrite(
...    [
...       { "updateOne": {
...          "filter": { "Name": "David", "Age": 22 },
...          "update": { "$set": { "Info": {Name:"John"} } }
...       }},
...       { "insertOne": {
...          "document": { "Name": "Carol", "Age": 22, "Info": {Name:"John"}}
...       }}
...    ],
...    { "ordered": false }
... )
{
   "acknowledged" : true,
   "deletedCount" : 0,
   "insertedCount" : 1,
   "matchedCount" : 1,
   "upsertedCount" : 0,
   "insertedIds" : {
      "1" : ObjectId("5e75f448bbc41e36cc3cae87")
   },
   "upsertedIds" : {
   }
}

Display all documents from a collection with the help of find() method −

> db.demo428.find();

This will produce the following output −

{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22, "Info" : { "Name" : "John" } }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e75f448bbc41e36cc3cae87"), "Name" : "Carol", "Age" : 22, "Info" : { "Name" : "John" } }

Updated on: 03-Apr-2020

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements