Reputation: 22101
Is there a way to list all the collection names and the document count for each collection in a single query?
The one that I could find only gives the count for a particular collection.
For example, if Users
was a collection then
db.Users.count()
Would give me the count of the number of documents in the collection Users
.
Upvotes: 9
Views: 8613
Reputation: 20712
No, there isn't. You have to use
var collections = db.runCommand({
listCollections:1,
filter:{ name:{ $not: /^system\..*/ } }
})
to get all collections created by the user and iterate over those 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);
}
Upvotes: -1
Reputation: 7698
If you just want to print the numbers and count, then 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, then you can use map function.
db.getCollectionNames().map(function(colName){
return {
"columnName":colName,
"count":db.getCollection(colName).count()
}
});
Upvotes: 2
Reputation: 50426
In the shell all you need to do is this:
db.getCollectionNames().map(function(name) {
return { "name": name, "count": db[name].count() }
})
There is no "command" and there is not "singular" collection query ( it is technically still multiple queries made for each collection, and a "source" query ) to do this since that is not how MongoDB stores the data. But there is a simple programitic method, and this is basically available to all drivers as well.
Upvotes: 11