有没有一种方法可以在单个查询中列出所有集合名称和每个集合的文档计数?
我找到的只能为特定集合提供计数。例如,如果 Users
是一个集合。
db.Users.count()
请给我这个集合 Users
中文档的数量。
有没有一种方法可以在单个查询中列出所有集合名称和每个集合的文档计数?
我找到的只能为特定集合提供计数。例如,如果 Users
是一个集合。
db.Users.count()
请给我这个集合 Users
中文档的数量。
在shell中,你只需要做这个:
db.getCollectionNames().map(function(name) {
return { "name": name, "count": db[name].count() }
})
由于MongoDB存储数据的方式不是这样的,所以没有“命令”和“单数”集合查询(从技术上讲,仍然是为每个集合进行多次查询,并使用“源”查询)。但是有一种简单的编程方法,基本上对所有驱动程序都可用。
db.getCollectionNames().forEach(function(colName){
print(colName+": "+db.collection(colName).count());
});
db.getCollectionNames().map(function(colName){
return {
"columnName":colName,
"count":db.getCollection(colName).count()
}
});
没有,你必须使用
。var collections = db.runCommand({
listCollections:1,
filter:{ name:{ $not: /^system\..*/ } }
})
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);
}
system.indexes
,而有效使用 map
也会发出多个查询。 - Markus W Mahlberg
db.getCollectionNames.map()
吗? - Vaulsteindb.getCollectionNames()
本身就是一个函数,它执行系统命令以返回“集合信息”。结果是一个适用于JavaScript中.map()
运算符的条件数组。正如你在这里应该“清楚地看到”的那样。对于返回的每个集合都会运行.count()
。这就是“它的工作方式”。正如我所说,返回“集合信息”的相同命令在每个驱动程序中都可用。 - Blakes Seven