MongoDB: Bulk insert (Bulk.insert) vs insert multi

2019-01-24 00:42发布

问题:

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?

回答1:

@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.



回答2:

Yes, there is difference. With bulk ops (always), you only need to go to the database once and you perform the operation on batches of records, then you return to the application. With individual inserts, you will need to go to the database, do the insert, then go back to the application, and you will repeat this process for every single insert operation you tell the database to perform. So individual inserts are very slow compared to the bulk operations. It is like groceries shopping, if you have everything you need to buy listed out, you can buy them all in one trip (bulk insert), but if for each item, you need to drive to the store to get it, and then drive home, then drive back to the store to buy another item, then it is not very efficient (like individual inserts)

Note: Even though, when interacting with MongoDB using the shell, you only need to deal with one insert function for bulk and individual inserts alike, you should make a distinction between insertOne() and insertMany() operations when using MongoDB driver APIs. And you should never call insertOne() inside a loop (reason: see my groceries shopping analogy above).



标签: mongodb