In MongoDB capped collections, do I have the guarantee that the _id
field is monotically increasing with the order of inserts? If not, how can I query for all the documents that were inserted after a given document? There shouldn't be any need for an index as I should be able to leverage their natural order.
Asked
Active
Viewed 575 times
3

Flavien
- 7,497
- 10
- 45
- 52
1 Answers
3
Part of ObjectId is a timestamp. So, if ObjectIds are always generated on the same machine (or otherwise time is consistent), then you are guaranteed monotonically increasing values. One caveat, though: timestamp is in seconds, not milliseconds. So, within the same second order of values is not guaranteed.
Capped collections support a special sorting option: $natural
. That means that documents will be returned in insertion order.
You can combine this with tailable cursors to continually fetch newly inserted documents without using any indexes (if that's what you're after).

Sergio Tulentsev
- 226,338
- 43
- 373
- 367
-
Ok, but how do I query starting from a document with specific ObjectId? I'm actually looking for a solution to restart a new tailable cursor after the previous one has gone bad, where it left off. – Flavien Jun 10 '12 at 10:04
-
Find it and then sort. I haven't tried myself, but should work. `db.cappedCollection.find({_id: {$gte: oid}}).sort({$natural:1}).limit(50)` – Sergio Tulentsev Jun 10 '12 at 10:07
-
You said there is no guarantee the OID follows the natural order, so that query is not gonna work. – Flavien Jun 10 '12 at 14:56
-
2You either need to include a createdAt timestamp in your documents to query on, or if you want to use the $natural insertion order, you'll need to fetch all the from the database and do the filter client-side. – stbrody Jun 11 '12 at 18:54