15

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.

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
@SushantGupta did you find answer of your comment ? if yes tell us i have same question
@babakfaghihian No, I didn't. You can go-ahead and ask. I would be glad to know the answer to it :)
@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?
@SushantGupta There is defined comparison order: docs.mongodb.com/manual/reference/bson-type-comparison-order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.