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?

2 Answers 2

3

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

val dbExists = !mongo.dbNames.contains("testXXX")
Sign up to request clarification or add additional context in comments.

2 Comments

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
Good point - in our context, we know we've only got at most tens of dbs.
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").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.