Get Number of Documents in MongoDB Index

Viewed 1582

As per the title, I would like to know if there is a way to get the number of documents in a MongoDB index.

To be clear, I am not looking for either of the following:

  • How to get the number of documents in a collection -- .count().
  • How to get the size of an index -- .stats().
1 Answers

An index references all of the documents in its collection unless the index is a sparse index or a partial index. From the docs:

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field. The index is “sparse” because it does not include all documents of a collection. By contrast, non-sparse indexes contain all documents in a collection, storing null values for those documents that do not contain the indexed field.

Partial indexes only index the documents in a collection that meet a specified filter expression

So ...

  • The answer for non sparse and non partial indexes is db.collection.count()

  • The answer for sparse and partial indexes could be inferred by running a query with no criteria, hinting on that index and then counting the results. For example:

      db.collection.find().hint('index_name_here').count()
    
Related