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.

db.collection.count(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();
3487  
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')}});
147  

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

Craig Derington

Full Stack Developer. Linux, Docker, Python, Celery, Flask, Django, Go, MySQL, MongoDB and Git. Modern, secure, high-performance applications capable of processing millions of transactions a day.

comments powered by Disqus