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))
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.
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.
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With