Cardinal $ins: MongoDB Query Performance over Ranges

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:


db.drivers.find({"country": {"$in": ["A", "G"]}).sort({"carsOwned": 1})


{"country": 1, "carsOwned": 1}

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:

db.collection.find({"country": {"$in": ["A", "G"]}}).sort({"carsOwned": 1})

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:

  1. First, fields on which you will query for exact values.
  2. Second, fields on which you will sort.
  3. 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!


(update: 2012-06-18 fixed quoting typos in diagram. -bw)

32 Responses to Cardinal $ins: MongoDB Query Performance over Ranges

  1. Sebastian 2012/06/13 at 11:08 pm #

    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?

  2. Eric Sedor 2012/06/14 at 9:38 am #

    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}.

  3. Daniel Galinkin 2012/06/14 at 2:50 pm #

    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)?

  4. Eric Sedor 2012/06/14 at 3:12 pm #

    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?

  5. Daniel Galinkin 2012/06/15 at 6:18 am #

    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!

  6. Luiz Mendes 2012/06/15 at 11:51 am #

    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:

     Let me show an example, there are 5 fields (Z,a,b,c,d) and we have to 
    get them using something like this:      “Z”: ObjectId(“someID”), 
         “a”: { 
             “$gte”: ISODate(“2012-04-25T03: 00: 00.0Z”), 
             “$lte”: ISODate(“2012-05-03T02: 59: 59.0Z”) 
           “b”: { 
             “$in”: { 
               “0”: 0, 
               “1”: 1, 
               “2”: 2 
            },      “d”: true, 
          “c”: { 
             “$in”: { 
               “0”: 2, 
               “1”: 0 
         “orderby”: { 
           “a”: -1 
        }, What is the best index for this case?  { -a,Z,b,c } 
     { Z,-a,b,c } 
     { Z,b,c,-a } Thanks 

  7. Eric Sedor 2012/06/15 at 12:41 pm #


    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!


  8. Luiz Mendes 2012/06/25 at 7:06 am #

    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

  9. Marcio 2013/02/22 at 5:58 am #

    Thank you, helpful a lot.

  10. Kevin Teljeur 2013/08/08 at 6:05 am #

    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.

  11. Eric Sedor 2013/08/12 at 2:31 pm #

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

  12. tpneumat 2013/08/23 at 7:43 am #

    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.

  13. ning 2014/01/16 at 1:57 am #


  14. Frank 2014/03/31 at 12:05 am #

    Hello ,Dear Eric:

    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.

  15. Eric Sedor 2014/03/31 at 1:23 pm #

    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.

  16. Pieter Willem Jordaan 2014/04/10 at 12:52 am #

    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?

  17. Pieter Willem Jordaan 2014/04/10 at 12:56 am #

    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.

  18. Eric Sedor 2014/04/10 at 8:33 am #

    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.

  19. Kevin Teljeur 2014/04/10 at 2:04 pm #

    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).

  20. Pieter Willem Jordaan 2014/04/15 at 7:13 am #

    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.

  21. Ginger 2014/07/04 at 4:04 pm #

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

  22. Juanjo Lainez Reche 2014/07/23 at 7:06 am #

    Great post!

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

  23. Adam Neumann 2015/03/06 at 9:59 pm #

    Thanks for the post, it really helped me out with some MongoDB related performance optimisations!

  24. Narendra 2016/12/11 at 6:49 am #

    Great post! I have a query though. Let’s say we have two fields.
    And we do a query: {a: {$in [a1, .. ,an]}, b: {$gt }}.sort({b : 1}).

    With a index [a, b], we can prune all the results with the first range query on a, then we must sort all of the sorted sub-sequences in memory before we return. The index on b is going to be use individually for each of the pruned results after the range query on the field a.

    If we have an index [b, a], are we going to have to scan all documents and check if the documents field a is one of [a1, .. an]? After we have narrowed down the range b > using the index.


  1. Introducing Dex: the Index Bot for MongoDB queries recommendations | MongoLab - MongoDB Hosting - 2012/06/19

    […] been cast as an automated tool.  For example, “Create indexes with this order: Exact values first. Sorted fields next. Ranged fields after that“.  It’s worked very well for us and we hope that it’ll work as well for your own […]

  2. [Forward] Things I wish I knew about MongoDB a year ago | Roger's Blog - 2012/10/22

    […] can read more about the issue or view […]

  3. How (well) does MongoDB integrate with Hadoop? - IKANOW | IKANOW - 2013/02/15

    […] “_id” ranges is actually surprisingly difficult because of a MongoDB issue described here and in this JIRA issue (but basically: you can’t sort on the secondary index, eg […]

  4. Production-Ready MongoDB | MongoLab: MongoDB-as-Service - 2013/08/27

    […] An advanced look at indexing […]

  5. Indexing MongoDB for quicker find() with sort(), on different fields - MongoDB Solutions - Developers Q & A - 2013/09/25

    […] ranges, like $in they suffer the same problem with indexes, this article should provide the answer: don’t really see any reason to repeat its […]

  6. MongoDB geospatial query with sort – performance issues | XL-UAT - 2015/03/10

    […] […]

  7. MongoDB Compound Index to Optimize Update with Key and Range Condition - BlogoSfera - 2015/07/28

    […] on my understanding on MongoDB doc and this article, I created index as per […]

  8. Форсаж под нагрузкой на Symfony HHVM MongoDB CouchDB Varnish - - 2016/01/24

    […] Так вот, это не совсем так. Вот универсальный алгоритм создания индексов, который позволяет использовать индексы и для запросов с выбором диапазонов значений (почему алгоритм именно такой, можно почитать здесь): […]

Leave a Reply