Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operate on all databases from the mongo shell

Tags:

mongodb

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.

like image 827
edebill Avatar asked Oct 16 '12 13:10

edebill


People also ask

How do I list all databases in mongo shell?

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.

Which of the following command can be used in mongo shell to show all the databases in your MongoDB instance?

8 Answers. Show activity on this post. Listing all the databases in mongoDB console is using the command show dbs .

Which command is used to open the MongoDB database shell?

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.


2 Answers

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
}
like image 58
JohnnyHK Avatar answered Sep 30 '22 17:09

JohnnyHK


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()); }
like image 26
davey Avatar answered Sep 30 '22 19:09

davey