Why should people ever use a single insertion method over a bulk insertion method?

66 views Asked by At

I'm working with a MongoDB database for a project, and I'm making some abstractions for interacting with it. MongoDB exposes the following methods for collections:

In terms of implementation, it's my understanding that the insertMany operation outperforms the inertOne operation, so the former section of code is prefered over the latter:

entries: list[object] = ...

# slower implementation
for entry in entries:
  collection.insert_one(entry)

# faster implementation
collection.insert_many(entries)

I've been writing some wrapping interfaces, though they're basically just a few lines in addition to the code above, so I'll leave those details out. But here, my question is, outside of coding conventions and readability, do I have any incentive to use the single insertion interface if I can just do the following?

# put a single entry into a list and add it to the collection using the batch method
collection.insert_many([entry])
1

There are 1 answers

2
Zack Newsham On

insertOne is marginally faster than insertMany at inserting a single document (in my very limit testing around 4-5% faster) - so in the case where you're inserting exactly one document, you should use insertOne - in the case where you're inserting many documents, you should use insertMany.

A second consideration is that insertMany will succeed or fail atomically - in most situations this is probably desirable, but if (for whatever reason) you expect some of your inserts to fail, but still want the rest to succeed, you'd want to use insertOne in a loop, with a try/catch.

^^ I now realise this portion of the answer was incorrect.