There are two possibilities to check if MongoDB database exists.
Case 1: The first possibility is that the MongoDB database exists i.e. it returns particular index.
Case 2: The second possibility is that the MongoDB database does not exist i.e. it returns index -1.
NOTE: An index starts from 0 and ends with (N-1) like an array.
The syntax is as follows to check if MongoDB database exists.
db.getMongo().getDBNames().indexOf("yourDatabaseName");
Case 1: Let us implement the above syntax to check if MongoDB database exists. Following is the query
db.getMongo().getDBNames().indexOf("test");
This will produce the following output
6
Look at the above sample output, we are getting 6 that means the database “test” exists and it is present at index 6.
Let us check all the databases now. Following is the query
> show dbs;
This will produce the following output
admin 0.001GB config 0.000GB local 0.000GB sample 0.001GB sampleDemo 0.000GB studentSearch 0.000GB test 0.009GB
Look at the above sample output, the database “test” exists and at index 6.
Case 2: If MongoDB database does not exist
> db.getMongo().getDBNames().indexOf("education");
The following is the output displaying -1 since the database “education” does not exist
-1