Does MongoDB successful insert guarantee populated ID's?

304 views Asked by At

We are using the MongoDB C# driver to insert a collection of records using InsertManyAsync.

We currently have code that iterates the entire collection after InsertManyAsync returns, confirming that the ID's are populated. I would expect that the driver takes care of this already, but I have not found documentation that says so.

If InsertManyAsync returns successfully (i.e., doesn't throw an exception), does the driver guarantee that the ID's of the provided collection are populated?

1

There are 1 answers

0
i3arnon On BEST ANSWER

Yes. If the operation completed without errors you are guaranteed that the documents have an ID (either created by you before the operation or by the driver in the operation itself).

Moreover, since the IDs are generated by the driver itself (client-side) before calling the MongoDB server there's a good change that the IDs are set even if there was an exception in the operation (e.g. the server was down).

The ID's are assigned by the MongoCollectionImpl.AssignId method that can be found here.