MongoDB query to add multiple documents


To perform multiple write operations, use bulkWrite(). Let us create an array list values. Following is the query −

> const arrayList = [
...    {"Value1":100, "Value2":200, "Name": "John"},
...    {"Value1":100, "Value2":200, "Name": "Bob"}
... ];
> let op1 = [];
> arrayList.forEach(({ Value1, Value2, Name }) => {
...    op1.push({
...       "updateOne": {
...          "filter": { Name},
...          "update": { "$set": { Value1, Value2, Name } },
...          "upsert": true
...       }
...    })
... });
> db.demo397.bulkWrite(op1);
{
   "acknowledged" : true,
   "deletedCount" : 0,
   "insertedCount" : 0,
   "matchedCount" : 0,
   "upsertedCount" : 2,
   "insertedIds" : {
   },
   "upsertedIds" : {
      "0" : ObjectId("5e5e8c07f995e1718151981c"),
      "1" : ObjectId("5e5e8c07f995e1718151981d")
   }
}

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

> db.demo397.find();

This will produce the following output −

{ "_id" : ObjectId("5e5e8c07f995e1718151981c"), "Name" : "John", "Value1" : 100, "Value2" : 200 }
{ "_id" : ObjectId("5e5e8c07f995e1718151981d"), "Name" : "Bob", "Value1" : 100, "Value2" : 200 }

Updated on: 02-Apr-2020

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements