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)