How to count the number of documents in a mongodb collection

前端 未结 8 1932
广开言路
广开言路 2020-12-29 04:49

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         


        
相关标签:
8条回答
  • 2020-12-29 05:43

    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/

    0 讨论(0)
  • 2020-12-29 05:44

    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.

    0 讨论(0)
提交回复
热议问题