问题
Whenever I run a count query on MongoDB with explain I can see two different stages COUNT_SCAN and IXSCAN. I want to know the difference between them according to performance and how can I improve the query. field is indexed.
query db.collection.explain(true).count({field:1}}) uses COUNT_SCAN and query like
db.collection.explain(true).count({field:"$in":[1,2]}) uses IXSCAN.
回答1:
The short: COUNT_SCAN is the most efficient way to get a count by reading the value from an index, but can only be performed in certain situations. Otherwise, IXSCAN is performed following by some filtering of documents and a count in memory.
When reading from secondary the read concern available is used. This concern level doesn't consider orphan documents in sharded clusters, and so no SHARDING_FILTER stage will be performed. This is when you see COUNT_SCAN.
However, if we use read concern local, we need to fetch the documents in order to perform the SHARDING_FILTER filter stage. In this case, there are multiple stages to fulfill the query: IXSCAN, then FETCH then SHARDING_FILTER.
来源:https://stackoverflow.com/questions/49554932/what-is-the-difference-between-count-scan-and-ixscan