Upsert many documents in MongoDB

MongoDBDatabaseBig Data Analytics

To upsert many documents, use UPSERT() with UPDATE(). Let us create a collection with documents −

> db.demo425.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e74ee4fbbc41e36cc3cae6c")
}
> db.demo425.insertOne({"Name":"David","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e74ee56bbc41e36cc3cae6d")
}
> db.demo425.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e74ee57bbc41e36cc3cae6e")
}
> db.demo425.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e74ee5cbbc41e36cc3cae6f")
}

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

> db.demo425.find();

This will produce the following output −

{ "_id" : ObjectId("5e74ee4fbbc41e36cc3cae6c"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e74ee56bbc41e36cc3cae6d"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e74ee57bbc41e36cc3cae6e"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e74ee5cbbc41e36cc3cae6f"), "Name" : "Chris", "Age" : 21 }

Following is the query to upsert many documents in MongoDB −

> var b1 = db.demo425.initializeUnorderedBulkOp();
> b1.find( { Name: "Chris" } ).upsert().update(
...    {
...       $setOnInsert: { id:101},
...       $set: { Name: "Robert", Age:23 }
...    }
... );
> b1.execute();
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 0,
   "nUpserted" : 0,
   "nMatched" : 3,
   "nModified" : 3,
   "nRemoved" : 0,
   "upserted" : [ ]
})

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

> db.demo425.find();

This will produce the following output −

{ "_id" : ObjectId("5e74ee4fbbc41e36cc3cae6c"), "Name" : "Robert", "Age" : 23 }
{ "_id" : ObjectId("5e74ee56bbc41e36cc3cae6d"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e74ee57bbc41e36cc3cae6e"), "Name" : "Robert", "Age" : 23 }
{ "_id" : ObjectId("5e74ee5cbbc41e36cc3cae6f"), "Name" : "Robert", "Age" : 23 }
raja
Published on 03-Apr-2020 13:54:53
Advertisements