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

后端 未结 2 510
悲&欢浪女
悲&欢浪女 2020-12-15 16:09

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

var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: \"abc12         


        
相关标签:
2条回答
  • 2020-12-15 16:53

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

    0 讨论(0)
  • 2020-12-15 17:04

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

    0 讨论(0)
提交回复
热议问题