问题
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