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])
insertOne
is marginally faster thaninsertMany
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 useinsertOne
- in the case where you're inserting many documents, you should useinsertMany
.A second consideration is thatinsertMany
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 useinsertOne
in a loop, with a try/catch.^^ I now realise this portion of the answer was incorrect.