paulkon
paulkon

Reputation: 1855

How does mongodb compare/sort by _id?

How does mongodb apply comparison operators and sorting on _ids? Does it do it by the timestamp portion of the _id? Also, does it make a difference if the objectId was generated on the client or server?

If so, would paging be reliable on this field? e.g. _id: { $gte: last_idOnPage }

Upvotes: 0

Views: 1585

Answers (2)

Salvador Dali
Salvador Dali

Reputation: 222541

Looking at the documentation about ObjectId() you can see that _id is a hexadecimal string which represents 12-byte number which consists of:

  • 4-byte value representing the seconds since the Unix epoch,
  • 3-byte machine identifier,
  • 2-byte process id, and
  • 3-byte counter, starting with a random value.

Therefore partially you are correct: it uses timestamp to sort values as well. But other parts are also used. Because this string represents a number, mongo just compares numbers to find which one is bigger.

Regarding your second question (does it makes a difference was _id generated by application layer or by database): it does not make any difference. Mongo still compares only numbers.

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Timestamp is the first portion of BSON::ObjectId value. So basically yes, it first sorts by timestamp and then by other parts.

Upvotes: 2

Related Questions