mongodbmongoidmongomappernosql

MongoDB: getting ObjectId of last inserted document with multiple, concurrent writers?


Consider the following scenario with MongoDB:

Three writers (A,B,C) insert a document into the same collection.

A inserts first, followed by B, followed by C.

How can we guarantee A retrieves the ObjectId of the document he inserted and not B's document or C's document? Do we need to serialize the writes (i.e., only permit B to write after A inserts and retrieves the ObjectId), or does MongoDB offer some native functionality for this scenario?

Thanks!

We're on Rails.


Solution

  • the normal pattern here is for the driver to allocate the ObjectId and then you know what it is for the insert even before the server gets it.