Skip to content

Instantly share code, notes, and snippets.

@dschenkelman
Created November 4, 2015 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dschenkelman/583de632a4925fed27a1 to your computer and use it in GitHub Desktop.
Save dschenkelman/583de632a4925fed27a1 to your computer and use it in GitHub Desktop.
Fighting with mongo's query planner

Index

db.{collection}.ensureIndex({ fieldA: 1, "nested.B": 1, "nested.C": 1 })

Bad query

db.{collection}.find({ fieldA: "abc", "nested.B": "123", "nested.C": "456"})

Only uses first two index fields and then individually scans all matching items for "nested.C": 1.

Good query

db.{collection}.find({ fieldA: "abc", "nested": { $elemMatch: { "B": "123", "C": "456" } })

Actually uses all three index fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment