There are two possibilities to check whether the MongoDB database exists.
Case 1: The first possibility is that the MongoDB database exists, that is, a specific index is returned.
Case 2: The second possibility is that the MongoDB database does not exist, that is, index -1 is returned.
Note: Indexing starts from 0 like an array and ends with (N-1).
The syntax is as follows, used to check whether the MongoDB database exists.
db.getMongo().getDBNames().indexOf("yourDatabaseName");
Case 1: Let us implement the above syntax to check if the MongoDB database exists. Following is the query
db.getMongo().getDBNames().indexOf("test");
This will produce the following output
6
Looking at the above example output, we get 6 which means database "test" exists and it appears at index 6.
Now let's check all databases. 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
Looking at the sample output above, the database "test" exists and has index 6.
Case 2: If the MongoDB database does not exist
> db.getMongo().getDBNames().indexOf("education");
The following is the output showing -1 because the database "education" does not exist
-1
The above is the detailed content of Check if MongoDB database exists?. For more information, please follow other related articles on the PHP Chinese website!