Get a count of the number of documents in the Mongodb collection

Is there a way to list all collection names and the number of documents for each collection in a single query?

The one I could find only gives an account for a particular collection. For example, if Users was a collection, then

 db.Users.count() 

Would give me a count of the number of documents in the Users collection.

+6
source share
3 answers

In the shell, all you need to do is the following:

 db.getCollectionNames().map(function(name) { return { "name": name, "count": db[name].count() } }) 

There is no “command”, and there is no “singular” collection request (this is technically still a few requests made for each collection, and a “source” request) to do this, since this is not how MongoDB stores the data. But there is a simple software method, and it is mostly available for all drivers.

+6
source

If you just want to print numbers and count, you can use forEach.

 db.getCollectionNames().forEach(function(colName){ print(colName+": "+db.collection(colName).count()); }); 

If you want to use it for any other operations, you can use the map function.

 db.getCollectionNames().map(function(colName){ return { "columnName":colName, "count":db.getCollection(colName).count() } }); 
+2
source

No no. You have to use

 var collections = db.runCommand({ listCollections:1, filter:{ name:{ $not: /^system\..*/ } } }) 

to get all user-created collections and iterate over these collections

 for (var index = 0; index < collections.length; index++) { var current = collections[index]; var doccount = db.runCommand({collStats:current,scale:1024,verbose:true}).count; print(current + ":" + doccount); } 
-1
source

All Articles