简体   繁体   English

给定特定记录,检索MongoDB集合中的上一个记录

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

I am fairly new to working with MongoDB. 我刚开始使用MongoDB。

I need to retrieve the previous record of a given record in a MongoDB collection. 我需要检索MongoDB集合中给定记录的先前记录。

  1. Is it possible to do this with "_id = ObjectId(...)" field? 是否可以通过“ _id = ObjectId(...)”字段来执行此操作?
  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. 在所有条件都相同的情况下, _id字段的默认值是一个ObjectId并且是单调的,或者一直在增加。

This means that given a known ObjectId value then the following is true to retrieve the document that was inserted immediately before it: 这意味着,给定一个已知的ObjectId值,则满足以下条件,以检索紧接在其之前插入的文档:

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). 唯一可能的变化是,各种源都在生成ObjectId值,并且它们的时钟设置为不同的时间(如完全不同的UTC时间)。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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