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

Is there a difference between volume insert vs multiple document insertion ?

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 it faster?

+10
mongodb
Jan 31 '16 at 9:17
source share
2 answers

@Dummy is true that bulk operations are generally faster than single inserts, however, since version 2.6 and above, pasting multiple documents using collection.insert is just syntactic sugar for BulkWrite . If you set the ordered flag to false, the performance should be identical to the unordered volume insert:

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

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

+19
Jan 31 '16 at 9:28
source share

Yes, there is a difference. When using massive options (always), you only need to enter the database once and perform the operation in batches of records, after which you will return to the application. With individual inserts, you will need to go to the database, paste, and then return to the application, and you will repeat this process for each individual insert operation that you specify to the database. Thus, individual inserts are very slow compared to mass operations. This is similar to grocery shopping, if you have everything you need to buy, you can buy them in one trip (bulk insert), but if for each item you need to drive to the store to get it, and then drive through home, then return to the store to buy another product, then it is not very effective (for example, individual inserts)

Note. Although when interacting with MongoDB using a shell, you only need to deal with one insert function for bulk and individual insertions, you must distinguish between insertOne() and insertMany() operations when using the MongoDB driver APIs. And you should never call insertOne() inside the loop (reason: see my product shopping analogy above).

+13
Jan 31 '16 at 9:22
source share



All Articles