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.
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.