I would like to know how to count the number of documents in a collection. I tried the follow
var value = collection.count();
&&
var value = collecti
Since v4.0.3 you can use for better performance:
db.collection.countDocuments()
db.collection.count(function(err,countData){
//you will get the count of number of documents in mongodb collection in the variable
countdata
});
In place of collection give your mongodb collection name
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/
Through MongoDB Console you can see the number of documents in a collection.
1.Go to mongoDB console and issue command "use databasename". To start the console go up to the bin folder of where MongoDB is installed and click on mongo.exe to start the mongoDB console e.g If the database is myDB then command is "use myDB"
2.Execute this command db.collection.count() collection is like table in RDBMS. e.g if your collection name is myCollection then the command is db.myCollection.count();
this command will print the size of the collection in the console.
Simply you can use
Model.count({email: 'xyz@gmail.com'}, function (err, count) {
console.log(count);
});