2010/10/11

Count all documents in database in Mongo

I needed to know total amount of documents in a given database in all collections,
excluding GridFS and other mongo internals. First attempt:

//get total amount of documents in database
var total = 0;
db.getCollectionNames()
    .filter(function(coll_name){
        return coll_name.indexOf('.') == -1;
    }).forEach(function(coll_name){
        total += db.getCollection(coll_name).count();
    });

print('Total amount of docs: ' + total);


To run it save it into file count.js and run mongo database_name count.js
But here comes the fun part - second way to do it:

#mongo database
> db.stats()
{
        "collections" : 130,
        "objects" : 4389872,
        "avgObjSize" : 648.2547217777649,
        "dataSize" : 2845755252,
        "storageSize" : 3507146240,
        "numExtents" : 454,
        "indexes" : 154,
        "indexSize" : 322494464,
        "fileSize" : 17105420288,
        "ok" : 1
}

No comments:

Post a Comment