mongodb select from different databases

倖福魔咒の 提交于 2019-12-10 18:14:07

问题


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

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

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


回答1:


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);

});


来源:https://stackoverflow.com/questions/31003922/mongodb-select-from-different-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!