2

Is there a way to check for the existence of Mongo Database via Java API without creating the database on initiating the call?

I am currently using Casbah (Scala Driver) to interact with our Mongo Instance

val mongo = MongoConnection(List(new ServerAddress("localhost",27017)))
val db = mongo.getDB("testXXX") 

The API getDB seems to create a database by default and I would not want this to occur

If testXXX does not exist, I would NOT want Mongo to create a database but instead let me as the consumer decide whether it exists

Is there such an API via MongoDB java driver or Casbah?

Cœur
  • 37,241
  • 25
  • 195
  • 267
conikeec
  • 209
  • 2
  • 14

2 Answers2

3

I'm using the following (also with Casbah / Scala):

val dbExists = !mongo.dbNames.contains("testXXX")
Kyrstellaine
  • 441
  • 5
  • 16
  • Might be an expensive operation if the instance contains over 100,000+ dbs .. I implemented a alternate solution where, I introspect if collection(s) exists and if not, I drop the created database .. Not the best solution but it does not involve linear search across all databases – conikeec Jun 28 '13 at 05:13
  • Good point - in our context, we know we've only got at most tens of dbs. – Kyrstellaine Jun 28 '13 at 14:48
2

By default the database won't be created on the server until you ask that database for a collection.

So you can do val db = mongo.getDB("testXXX") and a database called "testXXX" won't be created on your MongoDB server until you call something like db.getCollection("myCollectionName").

Trisha
  • 3,891
  • 1
  • 25
  • 39