mongodb 从不同的数据库中选择 [英] mongodb select from different databases

查看:38
本文介绍了mongodb 从不同的数据库中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约 200 个 mongodb 数据库.每个数据库都有一个名为Group"的集合,在这个集合中有一个名为meldingId"的字段.

I have about 200 mongodb databases. Every database has a collection called 'Group' and in this collection there is a field called 'meldingId'.

是否可以进行一个 mongodb 查询来查找不同数据库中的所有值.

Is it possible to make a one mongodb query which find all values in the different databases.

(我设法通过 selectDB($database_name) 选择数据库 bij 循环遍历数据库)

(I managed to select the databases bij looping through the databases by selectDB($database_name))

推荐答案

在 Mongo shell 中,这可以通过使用 db.getSiblingDB() 方法切换到管理数据库并通过运行获取 200 个数据库的列表管理命令 db.runCommand({ "listDatabases": 1 }).遍历数据库列表并使用 db.getSiblingDB() 再次在数据库之间切换,查询 Group 集合的 meldingId 值.像这样:

In Mongo shell, this can be done by using db.getSiblingDB() method to switch to admin database and get a list of the 200 databases by running the admin command db.runCommand({ "listDatabases": 1 }). Iterate over the list of databases and use db.getSiblingDB() again to switch between databases, query the Group collection for the meldingId values. Something like this:

// Switch to admin database and get list of databases.
db = db.getSiblingDB("admin");
dbs = db.runCommand({ "listDatabases": 1 }).databases;

// Iterate through each database.
dbs.forEach(function(database) {
    db = db.getSiblingDB(database.name);

    // Get the Group collection
    collection = db.getCollection("Group");

    // Iterate through all documents in collection.
    /*
        collection.find().forEach(function(doc) {

            // Print the meldingId field.
            print(doc.meldingId);
        });
    */

    var meldingIds = collection.distinct('meldingId');
    print(meldingIds);

});

这篇关于mongodb 从不同的数据库中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆