Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb select from different databases

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

like image 540
arjan kroon Avatar asked Jun 23 '15 13:06

arjan kroon


People also ask

How do I use another database in MongoDB?

You can use MongoDB Shell or MongoDB Compass to create a new database. MongoDB provides the use <database-name command to connect with the database. If the specified database name does not exist then it creates it and set it as a current database.

Can we do lookups in a different database mongoose?

It is not possible to query using lookup in two different db's. $lookup in mongodb supports Performs a left outer join to an unsharded collection in the same database. Save this answer.

Can you query multiple collections in MongoDB?

You can query multiple collections using the $lookup aggregation. I wrote an example here on the forum. Also, the Query Results Data Source can absolutely join results from several MongoDB queries. It doesn't matter which source database you used.

How do I select a database in MongoDB?

Open a new database connection. Open a connection to a new server using new Mongo() . Use getDB() method of the connection to select a database.


1 Answers

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

});
like image 114
chridam Avatar answered Oct 18 '22 22:10

chridam