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 = collection.find().count()
&&
var value = collection.find().dataSize()
I always get method undefined.
Can you let me know what is the method to use to find the total documents in a collection.
Thanks Ganesh
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.
Traverse to the database where your
collection
resides using the command:Then invoke the
count()
function on thecollection
in the database.and then
print(value)
or simplyvalue
, would give you the count of documents in the collection namedcollection
.Refer: http://docs.mongodb.org/v2.2/tutorial/getting-started-with-the-mongo-shell/
In place of collection give your mongodb collection name
Simply you can use
Execute Mongo shell commands in single line for better results.
To get count of all documents in mongodb
Output:
Available Documents count: 9
To get all count of document results in a collection
Output:
To get all dataSize of documents in a collection
Output:
If you want the number of documents in a collection, then use the
count
method, which returns a Promise. Here's an example:This assumes you're using Mongo 3.