Index optimization for MongoDB range queries
We know that MongoDB’s index is a B-Tree structure, which is very similar to MySQL’s index. So you should have heard this suggestion: When creating an index, you should consider the sort operation, and try to put the fields used by the sort operation behind your index. But in some cases, doing so will make your query performance lower. Question For example, we perform the following query: db.collection.find({“country”: “A”}).sort({“carsOwned”: 1}) The query condition is {“country”: “A”}, sorted by the positive order of the carsOwned field. So the index is easy to build, just create it directly country , carsOwned The joint index of the two fields is enough. like this: db.collection.ensureIndex({“country”: 1, “carsOwned”: 1}) Let’s look at a slightly more complex query: db.collection.find({“country”: {“$in”: [“A”, “G”]}}).sort({“carsOwned”: 1}) This time we want to query the data entries whose country is A or G, and the results are also sorted by the carsOwned field. If we also use the above index, and use explain() to analyze this query, we will find that in the output there is a “scanAndOrder” : true field, and the value of nscanned may be much larger than expected, even specifying limit has no effect. reason What is…