MongoDB - Count Query

This method returns the count on the number of documents in the collection that would match a find query. The db.collection.count() method does not perform the find() operation rather it counts the number of results that matches the query.


Additionally, you can also write the query...

MongoDB shell version: 3.0.5  
connecting to: test  
> db.people.find().count()

When counting on a index: consider the following:

{a: 1, b: 1}

When the MongoDB engine performs a count operation, it can return the count using only the index if the following conditions are met:

  • the query can use an index
  • the query only contains conditions on keys of the index, and;
  • the query predicates access to a single contigious range of keys.

This example shows the query using only an index.

MongoDB shell version: 3.0.5  
connecting to test  
> db.people.find({ a : 5, b : 5}).count();
> db.people.find({ a : { $gt : 5 }}).count();
> db.people.find({a : 5, b : { $gt : 10 }}).count();
Count all the documents in a collection
MongoDB shell version: 3.0.5  
connecting to test  
> db.people.count();
Count all the documents that match a query
MongoDB shell version: 3.0.5  
connecting to test  
> db.people.count({ created_date : { $gt : new Date('10/16/2015')}});

In the next chapter, we'll be working on some MongoDB insert queries.

Craig Derington

Espousing the virtues of Secular Humanism, Libertarianism, Free and Open Source Software, Linux, Ubuntu, CentOS, Terminal Multiplexing, Docker, Python, Flask, Django, MySQL, MongoDB and Git.

comments powered by Disqus