14

We can have { data: "hello" }, { data: 123 } in the same collection and even create a index on it. I'm curious how does mongodb manage the index behind the scene. We can't create single B-tree on different types. Right? However, I did getIndexes to see if another index is created but only one index is created.

Zaid Masud
  • 13,225
  • 9
  • 67
  • 88
Alice
  • 909
  • 1
  • 11
  • 15

1 Answers1

13

There's no problem having two types in the same index. Each key within the index includes the type.

When you query, only objects matching the type you query on will be returned.

So if you query for {data: "hello"}, only strings will be returned, etc.

Kyle Banker
  • 4,359
  • 23
  • 18
  • 8
    But while managing an index, we need comparison operations to be performed. How are different types compared in mongo. Does it take into account time of insertion in case of type mismatch or something similar? – Sushant Gupta Nov 23 '12 at 03:45
  • @SushantGupta did you find answer of your comment ? if yes tell us i have same question – babak faghihian Nov 22 '15 at 16:26
  • @babakfaghihian No, I didn't. You can go-ahead and ask. I would be glad to know the answer to it :) – Sushant Gupta Nov 23 '15 at 06:14
  • @Kyle Banker, we are aware of "no problem having two types in the same index". The question is about how MongoDB manages it. You write there's only one BTree that keeps the key's type along with a key. I find this solution is not optimal/simple compare to the solution with different BTrees for each value type that has the field. My downvote was rashly, but I can't withdraw it until you edit the answer. Could you add more information? – Evgeni Nabokov Feb 14 '20 at 19:15
  • 3
    @SushantGupta There is defined comparison order: https://docs.mongodb.com/manual/reference/bson-type-comparison-order/ – Evgeni Nabokov Feb 14 '20 at 23:34