How to count the number of documents in a mongodb

2020-05-25 05:40发布

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

标签: mongodb
8条回答
做个烂人
2楼-- · 2020-05-25 06:24

Since v4.0.3 you can use for better performance:

db.collection.countDocuments()
查看更多
我想做一个坏孩纸
3楼-- · 2020-05-25 06:32

db.collection('collection-name').count() is now deprecated. Instead of count(), we should now use countDocuments() and estimatedDocumentCount(). Here is an example:

`db.collection('collection-name').countDocuments().then((docs) =>{
console.log('Number of documents are', docs);
    };`

To know more read the documentation:

https://docs.mongodb.com/manual/reference/method/db.collection.countDocuments/

https://docs.mongodb.com/manual/reference/method/db.collection.estimatedDocumentCount/

查看更多
登录 后发表回答