Get the number of documents in a MongoDB collection with unique/distinct values for a field

Some times we need to get the number of documents with a distinct/unique value. An example use case is in the classic blog example.

  • Get the number of authors with at least one post.
  • Get the number of distinct tags/categories

You can use the following commands to get the answers for the above questions

db.posts.distinct('author').length
db.posts.distinct('tag').length

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *