w3resource

MongoDB: db.collection.count() method

db.collection.count

The db.collection.count() method is used to return the count of documents that would match a find() query. The db.collection.count() method does not perform the find() operation but instead counts and returns the number of results that match a query.

Syntax:

db.collection.count(query)

Parameters:

Name Description Required /
Optional
Type
query The query selection criteria. Required document

Note: The db.collection.count() method is equivalent to the db.collection.find(query).count() construct.

Sample document in the restaurants collection:


{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}
.....

Example: Count all document from the collection

Count the number of the documents in the restaurants collection.

db.restaurants.count(); 

Output:

> db.restaurants.count();
25359

Example : Count all Documents that Match a Query

Count the number of the documents in the restaurants collection with the field matching the cuisine is American:


db.restaurants.find({"cuisine" : "American "}).count() 

Output:

>db.restaurants.find({"cuisine" : "American "}).count();
6183

Example : Count all Documents that Match a Query using more than on criteria

Count the number of the documents in the collection restaurants filterring with the field cuisine is equal to Italian and zipcode is 10075:


db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } ).count();

Output:

> db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } ).count();
15

Behavior

Sharded Clusters

On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.

To avoid these situations, on a sharded cluster, use the $group stage of the db.collection.aggregate() method to $sum the documents.

Retrieve the restaurants data from here

Previous: db.collection.aggregate() method
Next: db.collection.createIndex() method



Follow us on Facebook and Twitter for latest update.