Can a query use multiple indexes?

db.col_name.createIndex({"A": 1})
db.col_name.createIndex({"B": 1})
db.col_name.find({A: 10, B: 50})

Will this query make use of both indexes? Is it doubly as efficient as just one index?

Hi @Big_Cat_Public_Safety_Act

MongoDB has an index intersection feature to do what you described. However in practice, it’s not as effective as, and not a replacement for proper compound index, and the query planner rarely chooses index intersection plans. For the exact query you posted, the best index would be db.collection.createIndex({A:1, B:1}) or db.collection.createIndex({B:1, A:1}). Which index to create would depend on what other queries you have so you can maximize index usage.

If you’re curious about MongoDB query index use, you can use db.collection.explain().find(....) to show the explain output of the query.

If you prefer to use a GUI, you can also use MongoDB Compass query plan view to see the explain output.

Best regards

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.