I am fairly new to working with MongoDB.
I need to retrieve the previous record of a given record in a MongoDB collection.
- Is it possible to do this with "_id = ObjectId(...)" field?
- If not, will we have to explicitly insert a key with a sequential value to identify the previous record to the given one? (Assume that there's no sequential key/value pair in the current collection)
Would greatly appreciate any help. Thank you.
All things being equal, the default value of the
_idfield is aObjectIdand is monotonic, or ever increasing.This means that given a known
ObjectIdvalue then the following is true to retrieve the document that was inserted immediately before it:That is the general case. The only possible variance is that various sources are producing the
ObjectIdvalues and their clocks are set to different times (as in completely different UTC times).So that coupled with the rate of insertion allows you to consider if this is good enough for you, and with the exception of rare and poorly managed conditions it should never be the case that the order is not always maintained.