Greetings adventurers! If you’ve been travelling through MongoDB indexing territory for any amount of time, you may have heard or derived the following maxim: If your queries contain a sort/orderby clause, add the sorted field to the end of the index servicing the query.

In many cases when querying for documents containing equivalent values, the above mantra is very helpful (by equivalency, I mean querying for a specific value in a field, such as {“name” : “Charlie”}). But what about the following:

This pairing is not as performant as one might expect, even though the index follows the maxim. That’s because there’s a very specific trap that this conventional wisdom may lead you into.

Below, we’ll walk through why that is, and by the end of this blog you’ll have a new rule of thumb to guide you when indexing. First though, while this is not a blog about basic indexing, let’s refresh ourselves on the basics distilled from the MongoDB documentation here:

“Index Early” Indexes deserve first-tier consideration in the design process. Efficiency at the data access level has historically been offloaded to a DBA-like role. which prompts the kind of post-design optimization layers that the document-oriented database stack still has the opportunity to avoid.

“Index Often”Indexed queries perform better by several orders of magnitude, even on small data. While an un-indexed query may take 10 seconds, the same query can take as little as 0 milliseconds given a proper index.

“Index Fully”Queries make use of indexes from left to right. An index can only be utilized to the extent that a query uses all of the fields in the index, and does not skip any.

“Index Sorts”
If your queries will contain a sort or orderby clause, add the sorted field to your index.

Commands

.explain() shows what index (if any) is used for a given query,

.ensureIndex() creates indexes,

.getIndexes() or .getIndexKeys() tell you what indexes you have.

Now, back to the question. Given indexing basics, conventional wisdom says that for the following query:

db.collection.find({“country”: “A”}).sort({“carsOwned”: 1})
We should create the following index:

db.collection.ensureIndex({"country": 1, "carsOwned": 1})

What if most queries to these fields are “range” checks instead of “equivalency” checks? As in:

We use $in here, but this applies to all range operators: $gt, $lt, etc.

If you see queries like this performing poorly, and you remember your basics, you’ll run a .explain() and see that see the index is being used. But you will also see {scanAndOrder : true}, revealing that MongoDB has performed an ordering operation. Here’s where the cost is. scanAndOrder is expensive because it sorts documents in memory. It should be avoided for large result sets because it’s slower and more CPU-intensive.

But forget about why scanAndOrder is slow; why would MongoDB order results if we’ve already accounted for the order in our index? Easy: We haven’t.

Why? The reason is simple and has to do with the structure of the index we created. For the example above, the documents having {“country”: “A”} and the documents having {“country”: “G”} are sorted–in the index–by {“carsOwned”: 1}, but they are sorted independently from each other. They’re not sorted together! Consider the diagram below:

The left-hand side of the diagram below shows the order thatMongoDB visits documents as it crawls the index we created. After documents matching all the criteria are found, the results must be ordered. The right-hand side shows an alternative index: { “carsOwned”: 1, “country”: 1}. By shifting the consideration of the sort field forward (leftward) in the index, we create a scenario where MongoDB visits the documents in the order we will ask for them. This subtle point of efficiency has led to the following rule of thumb when indexing:

The order of fields in an index should be:

First, fields on which you will query for exact values.

Second, fields on which you will sort.

Finally, fields on which you will query for a range of values.

Is there a trade-off? Yes. The query will visit more index nodes than it technically needs to, because traversal of the sort portion of the index will occur before pruning by the range criteria (“country”, in the example”). So, while we’ve seen this new rule of thumb as a net benefit for many queries, be aware that the cardinality of your data may yield different results.

I hope this guidance is helpful for you. Good luck out there, adventurers!

Subscribe

Related Posts:

But if I query db.collection.find({country ‘A’}) which index will be more performant {“country”: 1, “carsOwned”: 1} or {“carsOwned”: 1, “country”: 1}. will second index be used at all in such a query?

http://mongolab.com/ Eric Sedor

Your suspicion is correct. A query just on “country” cannot benefit from an index on {carsOwned: 1, country: 1}. The index must be used from left to right.

This points to the trade-off of optimizing to avoid scanAndOrder for an orderby query but ending up with a specialized index that other queries can’t use.
In the example you propose you would want an additional index just on {country: 1}.

Daniel Galinkin

What if I have a range and a sort on the same field in my query (and also other fields that I query for exact values)?

http://mongolab.com/ Eric Sedor

In this case, it should be safe to index the range/sort field last, after the exact value fields. As long as you have one sort field, you can think of it as collapsing items 2 and 3 in the final rule of thumb.

This becomes more awkward if you want to sort by two fields, but query a range on the second of the sort fields. In this case, a rule of thumb is not a substitute for proper experimentation and examination of your data cardinality.

Does that make sense?

Daniel Galinkin

Yeah, it does. That’s what we’ve been doing anyway: trying with different indexes configurations and testing them

Thanks a lot! Also, forgot to mention: great post!

Luiz Mendes

Hello Eric,

I work with Daniel and this index is a big problem for us. We have done some tests but we are not happy with the results.
We are planning a scripted test, testing almost all indexes with the most common queries. I think that it is not going to be possible to resolve our case entirely with only one index because its is not a static query, the user can choose which fields to search for.
At the end of the tests, we are going to come back here and tell you our conclusion, ok?Let me just explain our case in more details:

My estimation is that the index { Z: 1, a: -1, b: 1, c: 1 } will perform the best among these, for the following reasons:

1) The equivalency check on Z will immediately prune a lot of values at the first level of the index.
2) The ranges combined for fields b and c will already be ordered–collectively, by a, avoiding a scan and order of 3×2 buckets.

The potential challenges you face are actually based on the cardinality of a and the double-$ins on b and c. The broader the date range you allow in this query, the worse it is going to perform. Hopefully, the number of documents matching Z is small?

Depending on the other queries to this collection and the difficulty of maintaining this index compared to others, and if performance is a critical component of this query, I might recommend finding a more concrete way to represent b and c.

In any case I am glad you are willing to experiment with all three. Your tests will show whether the time saved by scanAndOrder is a net gain over the extra index time for traversing the a, b, c portion of the index. I am interested to hear your results!

Hopefully this helps!

Sincerely,
Eric@MongoLab

Luiz Mendes

Thank you for your answer.

Your estimation is the same as ours at the moment.
After the tests I will come here and post our conclusion in this case.Thanks again

We’ve already chatted on Twitter, but thanks again for a very informative article (with clear diagram) about a complex subject. The explanation of the relationship between indexes and sorting is very unclear in the MongoDB docs. It’s obvious in hindsight, of course. This article should in some form or fashion be the MongoDB docs article on indexing.

I have a collection of large documents, being queried on several keys (some nested). The results are sorted on several keys (some nested). The output:
Of what should have been 25 results of 378 (16 pages) I was getting none. Paging on 10 results, 5 pages out of 38. And that was it. I was getting memory-based errors which also prevent an explain from being output, but it was obviously an index-related issue, and related to the sorting of the results. Without a sort, I would get all the results. With a sort, I would get some some results and log an error.

If I hadn’t found this article, I would have had to drop MongoDB and find something else; I know people often make these trollworthy statements, but if I can’t get the results I need from a straightforward query (and with no good guidance as to why) with a system that is being designed for production, then I have to find something that can. So, again, thank you very much.

The controversial statement: The indexing mechanism itself needs to be sorted out. It’s easy to say, and I’m well aware that it’s non-trivial to do, but if order of index keys is critical, then the current indexing specification doesn’t really reflect that.

http://mongolab.com/ Eric Sedor

You’re most welcome, Kevin! Thank you for all your compliments.

Pieter Willem Jordaan

The criticality of order of index keys is a problem for any system utilizing a b-tree index, and is not something specific to mongodb alone.

Kevin Teljeur

The point was that indexing specification relies on key order, and in JavaScript/JSON objects (such as the index object) order is implicit, and should really be specified with, for example, an array, where ordering is explicit. It would help enormously.

My general comment was mostly about the fact that the documentation about how to structure a query in an optimal way was at that point very poor (I discussed it with people at MongoDB, and it has been updated since, by coincidence or not).

tpneumat

wow. That really helped. MongoDB indexes are quite tricky..easy to really mess up your app by doing them wrong. Thanks for the clear explanation–everyone using mongo should read this.

Could u help me on these. our department are using mongodb in our product.We are happy at its non-structure storage data and high performance at querying . However we have meet some problems.

On of them we meet is now we found we have create TOO MANY indexes .It’s because we need sort in many fields.

for example :our collection has many fields and in some scenarios we have to show more than 10 fields and about 8 fields are sortable . When we sort and page the data by some one of the field,we can get some error from the mongodb:[MongoDB – too much data for sort() with no index.](Our searching result may exceeds 10 thousands records. )

After searching the reason for it, we find that we have to create indexes on these fields.For example :the basic query condition are basic on these two field: A and B . But when we have to order by field C .we have to create a index like {C:1,A:1,B:1},when we order by field D,we have to create a indexes :{D:1,A:1,B:1},SO because we have about 8 fields need be sortable ,we have to create 8 such indexes I say above.This seems disgusting and the mongodb’s performance becomes bad when saving a document.

http://mongolab.com/ Eric Sedor

Supporting this kind of sort complexity can be a challenge. Here are the steps we would recommend:

1) First, attempt to index for each sort.

2) If the load problem is one of throughput, consider sharding to spread out both the read and write volume.

3) If the latency of each individual write operation is unacceptable, and that latency cannot be reduced by performance-tuning other aspects of the database. Consider moving the sorts outside of the database.

Pieter Willem Jordaan

Great post! For the case where the cardinality of the range values become an issue, how does the “optimal” order look like? 1: exact values, 2: range values, 3: sort?

http://mongolab.com/ Eric Sedor

That’s correct, Pieter, though unlikely. Usually that order is a fallback when other tradeoffs are involved, not when just a single query and index are considered.

Were this point reached, I would run tests with multiple index orders and throw rules of thumb out the window in favor of hard data. Just be sure that, having advanced to a scenario and infrastructure where you are crafting specific index orders based on the data itself, that the data is semi-regularly re-evaluated for new indexes, as cardinalities shift over time in many use-cases.

http://craftycode.co.za/ Pieter Willem Jordaan

Thank you, your answer makes a lot of sense! In our production server I’ve seen some queries taking longer than with our initial tests, due to the range field being more selective then, however in production now we see that the sorting impacts the performance immensely. I’m testing the index as your “optimal” order suggests, but I believe it will be better as you suggest.

Ginger

AWESOME!!!!!!! Thank you so much!!! I’ve been googling this for an answer for days!

Juanjo Lainez Reche

Great post!

But how it does apply when the first field is geoSpatial? The second field then is ignored, right?

About

This blog is brought to you by MongoLab, the fully-managed MongoDB Database-as-a-Service (DBaaS) platform that automates the operational aspects of running MongoDB in the cloud.