'How to run some shell command in few databases in mongodb
Suppose i have 1000's databases in mongo with names -
project1Db, rtDB1, config_1DB, config_2DB, config_3DB, project2Db, rtDB2 ...
All databases have some collections (i.e. x, y, z...)
Now i want to rename collection name of databases which name starts with config_{{somename}}
i.e. config_1DB, config_2DB, config_3DB databases have collection name student i want to rename that to person.
Brute force approach will be go to databases one by one and run command.
db.student.renameCollection("person")
Is there anyway to rename in all databases at once?
Solution 1:[1]
Could be like this:
db.adminCommand({ listDatabases: 1 }).databases.filter(x => x.name.startsWith("config_")).forEach(database => {
db.getSiblingDB(database.name).getCollectionNames().filter(x => x == "student ").forEach(col => {
db.getSiblingDB(database.name).getCollection(col).renameCollection("person");
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wernfried Domscheit |
