0

I am working with MongoDB and have a compound index on a collection, e.g., { a: 1, b: 1 }. I want to understand the performance implications when updating documents with respect to the fields in this index.

Specifically:

If I update the leading field (a) of a document, how does MongoDB handle the index update internally?

If I update the trailing field (b) instead, is the index update less costly?

Are there any best practices or considerations for designing compound indexes with frequently updated fields in mind?

I’m trying to understand whether it’s generally faster to update trailing fields than leading fields in a compound index, and why.

Any insights or references to MongoDB internals would be appreciated.

1
  • 1
    The old index entry has to be deleted and the new one inserted, except in the rare case when the new one can go exactly where the old one was. There is a lot more locality of reference when you only update the trailing part of the key, so there might be savings there. Commented Aug 22, 2025 at 1:41

1 Answer 1

5

In both cases, the update of the index is deleting a key and inserting the new one. What can make a little difference is when the old an new key is close enough, like in the same index block (their size is 16KB) because then it benefits from cache locality at different levels. For example, you have a key of {a: 10, b:10} and you set be so that it becomes {a: 10, b:11} there's good chances that it will be in the same block (except if there are thousands of documents with the same key of course).

However, this should not be the main reason for ordering fields in an index. The first reason is to serve more queries (for example if many queries filter on "a" only, it's best first). The second reason is better prefix compression (for example if "a" is large and have few different values, and "b" has many different values, it's better to keep "a" first).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.