Check if MongoDB database exists?

To check if a MongoDB database exists, use the indexOf() method on the list of database names. This returns the index position if the database exists, or -1 if it doesn't exist.

Syntax

db.getMongo().getDBNames().indexOf("databaseName");

Return Values

  • Positive number (0 or greater): Database exists at that index position
  • -1: Database does not exist

Case 1: Database Exists

Check if the "test" database exists ?

db.getMongo().getDBNames().indexOf("test");
6

The result 6 means the "test" database exists and is located at index 6 in the database list.

Verify Database List

View all existing databases to confirm ?

show dbs;
admin             0.001GB
config            0.000GB
local             0.000GB
sample            0.001GB
sampleDemo        0.000GB
studentSearch     0.000GB
test              0.009GB

The "test" database appears at index 6 (counting from 0: admin=0, config=1, local=2, sample=3, sampleDemo=4, studentSearch=5, test=6).

Case 2: Database Does Not Exist

Check for a non-existent database "education" ?

db.getMongo().getDBNames().indexOf("education");
-1

The result -1 confirms that the "education" database does not exist.

Key Points

  • Database indexing starts from 0 (like arrays)
  • Use this method for conditional logic in scripts
  • The getDBNames() method returns only databases with data

Conclusion

Use db.getMongo().getDBNames().indexOf("dbName") to check database existence. A non-negative result means the database exists, while -1 indicates it doesn't exist.

Updated on: 2026-03-15T00:38:06+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements