Home > Back-end >  Can Mongo Bulk Operations like insertMany Partially Fail?
Can Mongo Bulk Operations like insertMany Partially Fail?

Time:05-14

After scouring the documentation and posts online, there is one thing I have never been clear about with Mongo.

When you are attempting to write documents in bulk to a collection like the example below, is it ever possible that you would get some documents that write successfully, but some that don't?

db.products.insertMany( [
  { item: "card", qty: 15 },
  { item: "envelope", qty: 20 },
  { item: "stamps" , qty: 30 }
] );

In other words, could you ever get into a situation where you would create documents for the card and envelope items, but not for the stamps item?

I am trying to improve the performance of some of my company's processes and there is some debate in my team as to what kind of error scenarios can really arise from bulk inserts or updates, so if anyone has a clear answer, that would be fantastic. I know that generally mongo queries are not transactional unless you explicitly state so, but this is one area where it just wasn't clear.

CodePudding user response:

Have a look at this example:

db.products.insertMany([
   { _id: 1, item: "card", qty: 15 },
   { _id: 2, item: "envelope", qty: 20 },
   { _id: 1, item: "stamps", qty: 30 }
]);


uncaught exception: BulkWriteError({
    "writeErrors" : [
        {
            "index" : 2,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: so.products index: _id_ dup key: { _id: 1.0 }",
            "op" : {
                "_id" : 1,
                "item" : "stamps",
                "qty" : 30
            }
        },
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
}) :

Behavior should be obvious. Note, by default the documents are inserted in the same order as in your command, unless you specify option ordered: false

  • Related