Index tie breaks - implicit ordering on "_id"?

Hi there! I seem to recall reading somewhere that all indexes have an implicit “_id” field tacked onto the end of them to enforce consistent (albeit opaque) ordering even in case of ties.

  • Am I totally wrong about that? If so, the rest of this post doesn’t matter :slight_smile:
  • Someone mind pointing me to where I might have read this?
  • Is the implicit “_id” field ascending or descending?

Example collection:

[
  {_id: 1, name: "Sam"},
  {_id: 2, name: "Sam"},
  {_id: 3, name: "Paul"},
]

Example index: {name: 1} (is this technically {name: 1, _id: 1}?)
Would the index order consistently be

[
  {_id: 3, name: "Paul"}, 
  {_id: 1, name: "Sam"},
  {_id: 2, name: "Sam"},
]

Hi @Scott_Crunkleton ,

No. indexes do not include _id in them if you don’t explicitly state that on index creation…

The order of documents will probably be done on the natural insert order of the indexed documents, however without a proper sort statement the order is never guaranteed…

Thanks
Pavel

2 Likes

Thanks for the quick answer. I think I might’ve gotten that idea in my head since we use default mongo-generated ObjectIds, so our _ids ARE in the natural insert order.

How is insert order tracked when someone uses their own _id?

Do not rely on insert order. Always sort explicitly if the order is important.

2 Likes

Tie breaks in MongoDB with the same indexed field value are implicitly ordered by the “_id” field, which usually reflects insertion order.

My experience differs.

Do you have documentation that supports your assertion that _id is used to order documents without explicit sort.

@Pro_Hair_Tie, I asked for documentation that support your assertion.

Here is some documentation that supports mine.