How to count the number of documents in a mongodb collection

I would like to know how to count the number of documents in a collection. I tried to follow

var value = collection.count();
&&
var value = collection.find().count()
&&
var value = collection.find().dataSize()

I always get the method vague.

Could you let me know which method is used to find the total number of documents in the collection.

Thanks ganesh

+16
source share
7 answers

If you need the number of documents in the collection, use the method countthat Promise returns. Here is an example:

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

It is assumed that you are using Mongo 3.

+10
source

Browse to the database where you are collectionusing the following command:

use databasename;

Then call the function count()in collectionin the database.

var value = db.collection.count();

print(value) value collection.

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

+15

4.0.3 :

db.collection.countDocuments()
+4

      Model.count({email: 'xyz@gmail.com'}, function (err, count) {
      console.log(count);
    });
+3
db.collection.count(function(err,countData){

//you will get the count of number of documents in mongodb collection in the variable 
countdata

});

mongodb.

0

MongoDB .

1. mongoDB " ". , bin, MongoDB, mongo.exe. mongoDB , myDB, "use myDB"

2. db.collection.count() RDBMS. , myCollection, db.myCollection.count();

.

0

Mongo .

mongodb

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

: Available Documents count: 9

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

:

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 the data, the size of the documents in the 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
0
source

All Articles