We have a system with many different mongo databases. I regularly want to write ad-hoc queries that will apply to all (or a subset) of them, without having a priori knowledge of what databases are there.
I can do show dbs
, which will visually print a list, but is there a way to do something like:
var db_list = listDatabases();
for (i = 0; i < db_list.length; i++) {
do_something(db_list[i])
}
My problem with show dbs
is that it doesn't capture any return values, so I can't do anything productive with the output.
In MongoDB, you can use the show dbs command to list all databases on a MongoDB server. This will show you the database name, as well as the size of the database in gigabytes. You can select any database using the use statement and work on it.
8 Answers. Show activity on this post. Listing all the databases in mongoDB console is using the command show dbs .
To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.
You can use the 'listDatabases'
admin command for that:
var db_list = db.adminCommand('listDatabases');
That returns an object that looks like this:
{
"databases" : [
{
"name" : "test",
"sizeOnDisk" : 2097152000,
"empty" : false
},
{
"name" : "local",
"sizeOnDisk" : 1,
"empty" : true
}
],
"totalSize" : 8487174144,
"ok" : 1
}
There is also getDBNames() (i like how JohnnyHK's answer gets the size.
d = db.getMongo().getDBNames()
[ "graylog2", "local", "admin", "test" ]
Then I can:
for (var x in d) { db = new Mongo().getDB(d[x]); print(db); y = print(db.getCollectionNames()); }
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