How to count the number of documents in a mongodb collection

前端 未结 8 1975
广开言路
广开言路 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:27

    Execute Mongo shell commands in single line for better results.

    To get count of all documents in mongodb

    var documentCount = 0; db.getCollectionNames().forEach(function(collection) { documentCount++; }); print("Available Documents count: "+ documentCount);

    Output: Available Documents count: 9

    To get all count of document results in a collection

    db.getCollectionNames().forEach(function(collection) { resultCount = db[collection].count(); print("Results count for " + collection + ": "+ resultCount); });

    Output:

    Results count for ADDRESS: 250 
    Results count for APPLICATION_DEVELOPER: 950
    Results count for COUNTRY: 10
    Results count for DATABASE_DEVELOPER: 1
    Results count for EMPLOYEE: 4500
    Results count for FULL_STACK_DEVELOPER: 2000
    Results count for PHONE_NUMBER: 110
    Results count for STATE: 0
    Results count for QA_DEVELOPER: 100
    

    To get all dataSize of documents in a collection

    db.getCollectionNames().forEach(function(collection) { size = db[collection].dataSize(); print("dataSize for " + collection + ":"+ size); });

    Output:

    dataSize for ADDRESS: 250 
    dataSize for APPLICATION_DEVELOPER: 950
    dataSize for COUNTRY: 10
    dataSize for DATABASE_DEVELOPER: 1
    dataSize for EMPLOYEE: 4500
    dataSize for FULL_STACK_DEVELOPER: 2000
    dataSize for PHONE_NUMBER: 110
    dataSize for STATE: 0
    dataSize for QA_DEVELOPER: 100
    

提交回复
热议问题