17

In our code, for convenience, we use queries like

db.collection.find({ "field": { $in: array } })

even if array contains only a single element. We could have rewritten it in this case to simply be

db.collection.find({ "field": "element" })

We thought that these queries would behave the same, however we noticed that with complex queries, that contain $or operators and multiple fields, while explain() shows the same query plan for both cases, actually running the queries returns quickly for the simple case, while using $in takes forever because maybe it's using different index scans.

Why wouldn't the mongodb query compiler turn $in with a single element into the same as $eq? And why would explain() still show that they're using the same index scans and fetches, while actually running the queries obviously uses different plans?

1
  • What specific version of MongoDB server are you using, and what queries are you comparing? In your current description you mention "complex $or operators and multiple fields", which seems a separate question from $in with a single array element versus the equivalent equality criteria. It would also be helpful if you can link to a gist/pastebin/... with the output of explain(true) for the two queries you are comparing. Commented Apr 3, 2017 at 11:35

1 Answer 1

21

It's the same

use

.explain()

to see the final query

db.collection.find({ "field": { $in: array } }).explain()
db.collection.find({ "field": "element" }).explain()

the $in translated to $eq if array contains only 1 element

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.