Friday 4 June 2021

MongoDB: insertMany: Insert multiple documents to the collection

‘insertMany’ method is used to insert multiple documents into the collection.

 

Signature

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

 

Example

db.employee.insert([{"firstName" : "Shankar", "lastName" : "nzv"}, {"firstName" : "Rohini", "lastName" : "Shankar"}])

 

Let’s experiment with employee collection.


> db.employee.find().pretty()
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}

 

Let’s insert 2 new employee documents.

> db.employee.insert([{"firstName" : "Shankar", "lastName" : "nzv"}, {"firstName" : "Rohini", "lastName" : "Shankar"}])
BulkWriteResult({
      "writeErrors" : [ ],
      "writeConcernErrors" : [ ],
      "nInserted" : 2,
      "nUpserted" : 0,
      "nMatched" : 0,
      "nModified" : 0,
      "nRemoved" : 0,
      "upserted" : [ ]
})
> 
> 
> 
> db.employee.find().pretty()
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60bb062abaf44d88348459c6"),
      "firstName" : "Shankar",
      "lastName" : "nzv"
}
{
      "_id" : ObjectId("60bb062abaf44d88348459c7"),
      "firstName" : "Rohini",
      "lastName" : "Shankar"
}

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment