mongodb 从 mongo shell 操作所有数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12916183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:58:08  来源:igfitidea点击:

Operate on all databases from the mongo shell

mongodb

提问by edebill

We have a system with many different mongo databases. I regularly want to write ad-hoc queries that will apply to all (or a subset) of them, without having a priori knowledge of what databases are there.

我们有一个包含许多不同 mongo 数据库的系统。我经常想编写适用于所有(或一个子集)的即席查询,而无需先验了解那里的数据库。

I can do show dbs, which will visually print a list, but is there a way to do something like:

我可以做show dbs,它会在视觉上打印一个列表,但是有没有办法做这样的事情:

var db_list = listDatabases();

for (i = 0; i < db_list.length; i++) {
     do_something(db_list[i])
}

My problem with show dbsis that it doesn't capture any return values, so I can't do anything productive with the output.

我的问题show dbs是它没有捕获任何返回值,所以我不能对输出做任何有效率的事情。

回答by JohnnyHK

You can use the 'listDatabases'admin command for that:

您可以'listDatabases'为此使用admin 命令:

var db_list = db.adminCommand('listDatabases');

That returns an object that looks like this:

这将返回一个如下所示的对象:

{
    "databases" : [
        {
            "name" : "test",
            "sizeOnDisk" : 2097152000,
            "empty" : false
        },
        {
            "name" : "local",
            "sizeOnDisk" : 1,
            "empty" : true
        }
    ],
    "totalSize" : 8487174144,
    "ok" : 1
}

回答by davey

There is also getDBNames() (i like how JohnnyHK's answer gets the size.

还有 getDBNames() (我喜欢 JohnnyHK 的答案如何获得大小。

d = db.getMongo().getDBNames()
[ "graylog2", "local", "admin", "test" ]

Then I can:

然后我可以:

for (var x in d) { db = new Mongo().getDB(d[x]); print(db); y = print(db.getCollectionNames()); }