Mongodb choose from different databases

I have about 200 mongodb databases. Each database has a collection called "Group" and this collection has a "meldingId" field.

Is it possible to make one mongodb query that finds all values ​​in different databases.

(I was able to select bij databases going through databases using selectDB ($ database_name))

+3


source to share


1 answer


In Mongo shell, this can be done using the method to switch to admin database and get a list of 200 databases by running admin command . Go through the list of databases and use again to switch between databases, query collection for values . Something like that: db.getSiblingDB()

db.runCommand({ "listDatabases": 1 })

db.getSiblingDB()

Group

meldingId



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

});

      

+3


source







All Articles