How to count the number of documents in a mongodb collection

Since v4.0.3 you can use for better performance:

db.collection.countDocuments()

If you want the number of documents in a collection, then use the count method, which returns a Promise. Here's an example:

let coll = db.collection('collection_name');
coll.count().then((count) => {
    console.log(count);
});

This assumes you're using Mongo 3.

Edit: In version 4.0.3, count is deprecated. use countDocument to achieve the goal.


Execute Mongo shell commands in single line for better results.

To get count of all documents in mongodb

var documentCount = 0; db.getCollectionNames().forEach(function(collection) { documentCount++; }); print("Available Documents count: "+ documentCount);

Output: Available Documents count: 9

To get all count of document results in a collection

db.getCollectionNames().forEach(function(collection) { resultCount = db[collection].count(); print("Results count for " + collection + ": "+ resultCount); });

Output:

Results count for ADDRESS: 250 
Results count for APPLICATION_DEVELOPER: 950
Results count for COUNTRY: 10
Results count for DATABASE_DEVELOPER: 1
Results count for EMPLOYEE: 4500
Results count for FULL_STACK_DEVELOPER: 2000
Results count for PHONE_NUMBER: 110
Results count for STATE: 0
Results count for QA_DEVELOPER: 100

To get all dataSize of documents in a collection

db.getCollectionNames().forEach(function(collection) { size = db[collection].dataSize(); print("dataSize for " + collection + ":"+ size); });

Output:

dataSize for ADDRESS: 250 
dataSize for APPLICATION_DEVELOPER: 950
dataSize for COUNTRY: 10
dataSize for DATABASE_DEVELOPER: 1
dataSize for EMPLOYEE: 4500
dataSize for FULL_STACK_DEVELOPER: 2000
dataSize for PHONE_NUMBER: 110
dataSize for STATE: 0
dataSize for QA_DEVELOPER: 100

Traverse to the database where your collection resides using the command:

use databasename;

Then invoke the count() function on the collection in the database.

var value = db.collection.count();

and then print(value) or simply value, would give you the count of documents in the collection named collection.

Refer: http://docs.mongodb.org/v2.2/tutorial/getting-started-with-the-mongo-shell/

Tags:

Mongodb