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.
MongoDB Count Method is used to count the number of documents matching specified criteria. This method does not actually perform the find() operation, but rather returns a numerical count of the documents that meet the selection criteria.
count() The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional.
Python3. Method 2: count_documents() Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection. Example: Retrieves the documents present in the collection and the count of the documents using count_documents().
If you specify a maximum number of documents for a capped collection using the max parameter to create, the limit must be less than 2^32 documents. If you do not specify a maximum number of documents when creating a capped collection, there is no limit on the number of documents.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With