![]() |
VOOZH | about |
MongoDB is a popular NoSQL database that uses collections and documents, which are highly flexible and scalable. Unlike relational databases (RDBMS), MongoDB does not use tables and rows but stores data in a more dynamic, JSON-like format.
Here, we'll explore how to create a MongoDB database using the MongoDB Shell (mongosh) and cover related database operations.
To create a new MongoDB database using MongoDB Shell (mongosh) use the "use Database_Name" command. This command creates a new database if it doesn't exist, otherwise, it will return the existing database.
The newly created database will not be present in the list of databases. To display the database in the database list, insert at least one document into it.
Syntax:
use Database_Name
The below image shows new database creation using MongoDB Shell (mongosh):
👁 ImageIn MongoDB default database is test. If you did not create any Database and started inserting collection then all collections are stored in the Default Database.
To view a list of all existing MongoDB databases, use the following command:
show dbsThis will return a list of all databases currently stored in MongoDB. Note that if your new database doesn't contain any collections, it won’t appear in this list until you add a document to it.
The below example shows how to see list of databases using MongoDB Shell (mongosh).
👁 show list of databases exampleTo check the current database you're working with, simply use the following command:
dbThis will return the name of the database that’s currently active. If you’ve just created a new database, it will return the name of the newly selected database.
The below image shows how to check current database using MongoDB Shell (mongosh).
👁 check current database exampleTo switch to a different database, use the use command again followed by the name of the desired database. If the database does not exist, MongoDB will create it:
use AnotherDBThe below image shows how to switch to another database using MongoDB Shell (mongosh).
👁 switch to other database exampleIn the above Example, First we check current Database name using db command which was UserDB then we use "use test" command to switch to database test.
Once you’ve created your database, you can insert a document into a collection to make the database visible in the database list. Here’s an example of inserting a document into a new collection:
db.users.insertOne({ name: "John Doe", age: 30 })Once we insert a document, the TestDB database will appear in the list of databases when we run the show dbs command.