Thursday 3 August 2023

BulkWrite/BulkInsert Operation in MongoDB

 BulkWrite Operation in simple word perform CRUD operation in single collection. Which is mainly use in sharding but you can do in single node on single collection also below the command/Syntax.

> db.collection.bulkWrite()

Supports the following write operations:

  • insertOne
  • updateOne
  • updateMany
  • replaceOne
  • deleteOne
  • deleteMany

try {
db.student.bulkWrite(
   [
        { insertOne : { “document” : {“name” : “Dimitry”, “rollno” : 106, “contact” : “89xxxxxxxx”}}}},
        { insertOne : { “document” : {“name” : “Dorian”, “rollno” : 107, “contact” : “88xxxxxxxxxx”}}},
        { updateOne : { “filter” : { “rollno” : 105 },”update” : { $set : { “name” : “Test Name” }}}},
        { deleteOne : { “filter” : { “rollno” : 101}}},
        { replaceOne :{ “filter” : { “rollno” : 102 },”replacement” : { “name” : “Karan”, “contact” : “77xxxxxxxxxx” }}}
   ]
);
}
catch (e) {
print(e);
}

 

BulkInsert Command 

> db.student.insertMany()

 

try {
   db.student.insertMany( [
          { “name”: “A”, “rollno” : 201 },
          { “name”: “B”, “rollno” :202 },
          { “name”: “C”, “rollno” :203 },
          { “name”: “D”, “rollno” :204 },
          { “name”: “E”, “rollno” :205 }
] );
} catch (e) {
print (e);
}

 

For more details about BulkWrite/BulkInsert: Click Here

No comments: