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.
This operator represents the scanning of an index. Operator name: IXSCAN. Represents: The scanning of an index to produce a reduced stream of row IDs. The scanning can use optional start/stop conditions, or might apply to indexable predicates that reference columns of the index.
MongoDB runs the query optimizer to choose the winning plan, executes the winning plan to completion, and returns statistics describing the execution of the winning plan. cursor.
The explain command provides information on the execution of the following commands: aggregate , count , distinct , find , findAndModify , delete , mapReduce , and update .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With