Flavien
Flavien

Reputation: 8127

MongoDB capped collection and monotically increasing index

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.

Upvotes: 3

Views: 609

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

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).

Upvotes: 3

Related Questions