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?
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.
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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With