Checking for database and/or collection existence when scripting the shell

651 views
Skip to first unread message

KT

unread,
May 12, 2011, 1:41:49 PM5/12/11
to mongod...@googlegroups.com
Is there any way to check if a database or collection exists before performing operations on it?

I'm trying to write some shell scripts to automate some tasks. I'm passing in arguments to the script by defining an args array with the necessary arguments, which includes the db name and collection name. However, if either name isn't correct it creates the db or collection. I'd like to detect and raise a warning if the specified db or collection doesn't exist.

Or is there a better way to do something like this? I need to perform the same operations on new collections as I receive them.

Bernie Hackett

unread,
May 12, 2011, 1:49:52 PM5/12/11
to mongodb-user
There are queries you can run to get this information:

> use admin
switched to db admin
> db.runCommand("listDatabases")
{
"databases" : [
{
"name" : "test",
"sizeOnDisk" : 218103808,
"empty" : false
},
{
"name" : "pymongo_test_bernie",
"sizeOnDisk" : 218103808,
"empty" : false
},
{
"name" : "example",
"sizeOnDisk" : 218103808,
"empty" : false
},
{
"name" : "admin",
"sizeOnDisk" : 218103808,
"empty" : false
},
{
"name" : "foo",
"sizeOnDisk" : 1,
"empty" : true
},
{
"name" : "local",
"sizeOnDisk" : 1,
"empty" : true
}
],
"totalSize" : 872415232,
"ok" : 1
}

> use test
switched to db test
> db.system.namespaces.find()
{ "name" : "test.stuff" }
{ "name" : "test.system.indexes" }
{ "name" : "test.stuff.$_id_" }
{ "name" : "test.foo" }
{ "name" : "test.foo.$_id_" }


Most of the drivers should provide a way to run commands like
'listDatabases'. You should be able to query on db.system.namespaces
in all the drivers.

KT

unread,
May 12, 2011, 3:54:18 PM5/12/11
to mongod...@googlegroups.com
Perfect. Thank you.

So if I wanted to create a stored function to evaluate if the db/collection exists (in db.system.js) is the only way to call that function with db.eval()?

Bernie Hackett

unread,
May 13, 2011, 6:02:30 PM5/13/11
to mongodb-user
db.eval() would be the correct way to do that.
Reply all
Reply to author
Forward
0 new messages