Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Bulk insert (Bulk.insert) vs insert multiple (insert([...]))

Tags:

mongodb

Is there any difference between a bulk insert vs inserting multiple documents?

var bulk = db.items.initializeUnorderedBulkOp(); bulk.insert( { item: "abc123", defaultQty: 100, status: "A", points: 100 } ); bulk.insert( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } ); bulk.insert( { item: "mop123", defaultQty: 0, status: "P", points: 0 } ); bulk.execute(); 

VS

db.collection.insert(    <document or array of documents> ) 

Is there one thats faster?

like image 387
Jiew Meng Avatar asked Jan 31 '16 09:01

Jiew Meng


People also ask

What is bulk insert in MongoDB?

Multiple documents can be inserted at a time in MongoDB using bulk insert operation where an array of documents is passed to the insert method as parameter.

What is the difference between insertOne and insertMany?

With insertOne you can insert one document into the collection. insertMany accepts an array of documents and these are inserted. The insert (the method from older versions) takes a single document by default, and there is an option to insert multiple documents supplied as an array.

Which method is used to insert multiple documents in MongoDB?

insertMany() can insert multiple documents into a collection. Pass an array of documents to the method. The following example inserts three new documents into the inventory collection. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.


1 Answers

@Dummy is correct that bulk operations are generally faster than individual inserts, however, from version 2.6 and above, inserting multiple documents using collection.insert is just syntactic sugar for a BulkWrite. If you set the ordered flag to false, performance should be identical to an unordered bulk insert:

db.collection.insert(<document array>,{ordered:false}) 

This operation will return a BulkWriteResult, see more details in the documentation.

like image 140
Alex Avatar answered Sep 19 '22 21:09

Alex