Skip to main content

MongoDB Creating Database with mongosh

MongoDB: Creating a Database with mongosh

  • Creating a database in MongoDB is a fundamental step for organizing and managing your data efficiently.
  • This tutorial explains how to create a new database using mongosh, the modern MongoDB command-line shell.

1. Introduction to mongosh

mongosh is MongoDB's official interactive shell that allows you to run commands and manage your databases. It provides an intuitive and powerful interface for performing database operations directly from the terminal or command prompt.


2. Steps to Create a Database with mongosh

Follow these steps to create a new database:

  1. Start Your MongoDB Server: Ensure your MongoDB server (mongod) is running locally or your remote MongoDB instance is accessible.
  2. Open Terminal or Command Prompt: Access your command-line interface on your system.
  3. Launch the mongosh Shell: Enter the command below to start the MongoDB shell and connect to the local instance by default:
mongosh

Once inside mongosh, you can interact with your MongoDB server.


3. Creating and Switching to a Database

In MongoDB, databases are created implicitly. When you switch to a database that does not exist, MongoDB will create it upon the first write operation.

To select or create a database, use the use command followed by your desired database name:

use myDatabase

Replace myDatabase with the database name you want to create or use. This command switches the shell's context to the specified database.

Note: At this stage, the database is not yet physically created on the server. It will be created when you insert your first document or collection.


4. Verifying Database Creation

To see all existing databases on your MongoDB server, execute:

show databases

Your new database will appear in this list only after it contains data.

To create the database immediately, you can create a collection and insert a document:

db.myCollection.insertOne({ name: "First Document" })

This inserts a document into a collection named myCollection in the current database (which was switched to using use myDatabase) and causes the database to be created.


5. Recap: Common Commands

Command Description
mongosh Starts the MongoDB shell connected to the local server.
use <databaseName> Switches to the specified database. Creates it on first write.
show databases Lists all databases with existing data.
db.<collectionName>.insertOne(document) Inserts a single document into the specified collection, creating the DB and collection if needed.

Comments