DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Cardinal $ins: MongoDB Query Performance Over Ranges

Cardinal $ins: MongoDB Query Performance Over Ranges

Eric Sedor user avatar by
Eric Sedor
·
Sep. 19, 12 · Interview
Like (1)
Save
Tweet
Share
17.35K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Query

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

Index

{"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!

Sincerely,
Eric@MongoLab

Database MongoDB

Published at DZone with permission of Eric Sedor, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Use Terraform to Provision an AWS EC2 Instance
  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • Top Five Tools for AI-based Test Automation
  • Visual Network Mapping Your K8s Clusters To Assess Performance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: