Home > Database > MongoDB > body text

Check if MongoDB database exists?

PHPz
Release: 2023-09-23 20:21:03
forward
1046 people have browsed it

Check if MongoDB database exists?

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");
Copy after login

Case 1: Let us implement the above syntax to check if the MongoDB database exists. Following is the query

db.getMongo().getDBNames().indexOf("test");
Copy after login

This will produce the following output

6
Copy after login

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;
Copy after login

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
Copy after login

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");
Copy after login

The following is the output showing -1 because the database "education" does not exist

-1
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!