简体   繁体   中英

Given a particular record, retrieving the previous one in a MongoDB collection

I am fairly new to working with MongoDB.

I need to retrieve the previous record of a given record in a MongoDB collection.

  1. Is it possible to do this with "_id = ObjectId(...)" field?
  2. 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 _id field is a ObjectId and is monotonic, or ever increasing.

This means that given a known ObjectId value then the following is true to retrieve the document that was inserted immediately before it:

db.collection.find(
    { "_id": { "$lt": ObjectId("538c271a19b3a188ca6135eb") }}
).sort({ "_id": -1 }).limit(1)

That is the general case. The only possible variance is that various sources are producing the ObjectId values 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.

May i suggest use indexes for best performance.

As an example: Create Indexes:

db.books.ensureIndex({book: 1}) // for next records in collection
db.books.ensureIndex({book: -1}) // for previous records in collection

Next query looks like:

db.books.find({book: {$gt:"a"}}).sort({book: 1}).hint({book: 1}).limit(1)

Previous query looks like:

db.books.find({book: {$lt:"b"}}).sort({book: -1}).hint({book: -1}).limit(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM