Paramclasses Academy - Blog

Tutorials Details

←
Post 8 of 35
→

MongoDB Shell (mongosh) Tutorial: Connect and Run Your First Commands

MongoDB Shell (mongosh) Tutorial: Connect and Run Your First Commands

November 5, 2026

MongoDB Shell (mongosh) Tutorial: Connect and Run Your First Commands

❖ Welcome to Param Classes!

MongoDB is a popular NoSQL database used for storing and managing application data. Developers need an easy way to communicate with MongoDB, execute queries and manage database records.

The MongoDB Shell (mongosh) is an interactive command-line tool that allows developers to connect to MongoDB databases and execute commands directly.

Unlike MongoDB Compass, which provides a graphical user interface, mongosh allows you to work with databases using commands.

In this beginner-friendly tutorial by Param Classes, you will learn how to install MongoDB Shell, connect to a local MongoDB server, understand basic shell commands, create databases and collections, insert documents, retrieve records, update data, delete documents and connect to MongoDB Atlas.

✦ 1. What Is MongoDB Shell (mongosh)?

MongoDB Shell, also known as mongosh, is an interactive JavaScript and Node.js-based environment used to communicate with MongoDB databases.

It allows developers to perform database operations directly through a command-line interface.

Using mongosh, you can create databases, manage collections, insert documents, retrieve information and execute queries.

Some important features of MongoDB Shell are:

  • Connect to local MongoDB databases.

  • Connect to MongoDB Atlas cloud databases.

  • Create and manage databases.

  • Create and manage collections.

  • Insert single and multiple documents.

  • Retrieve documents using queries.

  • Update existing records.

  • Delete unwanted documents.

  • Execute JavaScript expressions.

  • Run database commands and scripts.

MongoDB Shell is useful for beginners, developers and database administrators who want to manage MongoDB through commands.

✦ 2. What Is the Difference Between MongoDB Compass and mongosh?

MongoDB provides different tools to interact with databases. Two commonly used tools are MongoDB Compass and MongoDB Shell.

MongoDB Compass: It is a graphical database management tool that allows users to view and manage databases through a visual interface.

MongoDB Shell (mongosh): It is a command-line tool that allows users to execute MongoDB commands directly.

MongoDB Compass MongoDB Shell
Graphical user interface Command-line interface
Uses visual controls Uses commands
Beginner-friendly visual experience Useful for command-based learning
Displays documents visually Displays query results in the terminal
Supports database management Supports database management and scripting

Both tools help developers work with MongoDB, but they provide different ways of interacting with databases.

✦ 3. Download MongoDB Shell (mongosh)

Before running MongoDB commands, you need to install MongoDB Shell on your computer.

Step 1: Open the official MongoDB download website:

https://www.mongodb.com/try/download/shell

Step 2: Select MongoDB Shell (mongosh).

Step 3: Choose your operating system, such as Windows.

Step 4: Select the appropriate download package.

Step 5: Download the installer.

Step 6: Open the downloaded setup file and follow the installation instructions.

Step 7: Complete the installation process.

MongoDB Shell is a separate tool from the MongoDB database server. If you have installed MongoDB Community Server, verify whether mongosh is already available on your computer.

✦ 4. Verify MongoDB Shell Installation

After installing mongosh, we need to verify whether it is working correctly.

Step 1: Open Command Prompt on Windows.

Step 2: Type the following command:

mongosh --version

Step 3: Press Enter.

If mongosh is installed correctly and available in your system PATH, the terminal will display its installed version.

You can also check the available command-line options using:

mongosh --help

Note: If Windows displays an error saying that mongosh is not recognized, check the installation location and PATH configuration. You may also need to reopen Command Prompt after installation.

✦ 5. Start MongoDB Server

Before connecting mongosh to a local database, make sure MongoDB Community Server is installed and running.

MongoDB Shell is a client tool. It does not start the database server by itself.

On Windows, follow these steps:

Step 1: Press Windows + R.

Step 2: Type:

services.msc

Step 3: Press Enter.

Step 4: Find the MongoDB Server service in the Services window.

Step 5: Check whether the service is running.

Step 6: If it is stopped, right-click the service and select Start.

Once the MongoDB server is running, you can connect to it through mongosh.

Important: The service name and installation configuration may differ depending on how MongoDB was installed.

✦ 6. Connect to MongoDB Using mongosh

Now let's establish our first connection to a local MongoDB server.

The default local MongoDB connection address is:

mongodb://127.0.0.1:27017

Here:

  • mongodb:// identifies the MongoDB connection protocol.

  • 127.0.0.1 represents your local computer.

  • 27017 is the default MongoDB server port.

Step 1: Open Command Prompt.

Step 2: Enter the following command:

mongosh "mongodb://127.0.0.1:27017"

Step 3: Press Enter.

If your MongoDB server is running and the connection is configured correctly, mongosh will connect to your local database server.

You will see a shell prompt where you can start entering MongoDB commands.

Example:

test>

The prompt may show the name of the currently selected database.

Congratulations! You have successfully connected MongoDB Shell with your local MongoDB server.

✦ 7. Understand Your First MongoDB Shell Commands

After connecting to MongoDB, you can execute different commands directly in mongosh.

Let's understand some basic commands.

1. Check the Current Database

db

This command displays the name of the currently selected database.

2. Display All Databases

show dbs

This command displays the databases available on the connected MongoDB server.

3. Display Collections

show collections

This command displays the collections available in the current database.

4. Display Available Help

help

This command displays general information about available shell commands.

5. Check MongoDB Server Information

db.version()

This command displays the version of the connected MongoDB server.

These commands help beginners understand how to navigate and interact with MongoDB through the shell.

✦ 8. Create a Database Using the use Command

Now let's create our first database using mongosh.

For this practical example, we will create a database for a college student management system.

Database name:

college

Step 1: Open MongoDB Shell.

Step 2: Execute the following command:

use college

Step 3: Press Enter.

You will see a message indicating that the shell has switched to the college database.

Important: The use command switches to the specified database. MongoDB generally creates the database when data is first stored or a collection is created.

To check the currently selected database, use:

db

Expected output:

college

You have now selected your college database.

✦ 9. Create a Collection Using createCollection()

A collection is a group of MongoDB documents.

In a relational database, a collection is somewhat similar to a table.

For our student management system, we will create a collection named:

students

Step 1: Make sure the college database is selected.

use college

Step 2: Run the following command:

db.createCollection("students")

Step 3: Press Enter.

Expected output:

{ ok: 1 }

This indicates that the collection was created successfully.

To display all collections, execute:

show collections

Expected output:

students

Your database structure will now look like this:

college
    |
    └── students

✦ 10. Insert a Single Document Using insertOne()

Now let's insert our first student record into the students collection.

MongoDB provides the insertOne() method to insert one document.

Example:

db.students.insertOne({
    name: "Rahul Kumar",
    age: 22,
    course: "MongoDB",
    city: "Raipur",
    status: "Active"
})

Explanation:

  • db.students selects the students collection.

  • insertOne() inserts a single document.

  • name stores the student's name.

  • age stores the student's age.

  • course stores the course name.

  • city stores the student's city.

  • status stores the student's current status.

After executing the command, MongoDB will return an inserted ID.

Example output:

{
    acknowledged: true,
    insertedId: ObjectId("...")
}

This means the student document was inserted successfully.

✦ 11. Insert Multiple Documents Using insertMany()

If you want to insert multiple student records at the same time, you can use the insertMany() method.

Example:

db.students.insertMany([
    {
        name: "Priya Sharma",
        age: 21,
        course: "Python",
        city: "Bilaspur",
        status: "Active"
    },
    {
        name: "Amit Verma",
        age: 23,
        course: "Java",
        city: "Raipur",
        status: "Active"
    },
    {
        name: "Neha Sahu",
        age: 22,
        course: "Node.js",
        city: "Durg",
        status: "Inactive"
    }
])

Explanation:

  • insertMany() inserts multiple documents.

  • Each object represents one student record.

  • MongoDB automatically generates a unique _id for each document when one is not provided.

After execution, MongoDB displays the insertion result and the IDs of the inserted documents.

This method is useful when adding multiple records to a database.

✦ 12. Retrieve All Documents Using find()

After inserting records, let's retrieve all student information.

MongoDB provides the find() method to search and retrieve documents.

Example:

db.students.find()

This command displays all documents stored in the students collection.

For a more readable output, use:

db.students.find().pretty()

The shell displays matching documents in a formatted manner.

Explanation:

  • db.students selects the students collection.

  • find() retrieves documents.

  • Empty braces {} can be used to retrieve all documents.

Example:

db.students.find({})

Both commands retrieve all documents from the collection.

✦ 13. Retrieve Specific Records Using find()

Sometimes you do not need all student records. You only want documents matching a particular condition.

For example, find students who belong to Raipur.

db.students.find({
    city: "Raipur"
})

To find students enrolled in MongoDB:

db.students.find({
    course: "MongoDB"
})

To find active students:

db.students.find({
    status: "Active"
})

These queries help retrieve specific records from the collection.

✦ 14. Retrieve a Single Document Using findOne()

If you want to retrieve only one matching document, use the findOne() method.

Example:

db.students.findOne({
    name: "Rahul Kumar"
})

This command returns the first matching student document.

You can also search using another field:

db.students.findOne({
    course: "Python"
})

The findOne() method is useful when you need to retrieve a single record instead of multiple documents.

✦ 15. Update Documents Using updateOne()

Suppose Rahul Kumar changes his course from MongoDB to Node.js.

We can update his existing record using the updateOne() method.

Example:

db.students.updateOne(
    {
        name: "Rahul Kumar"
    },
    {
        $set: {
            course: "Node.js"
        }
    }
)

Explanation:

  • updateOne() updates one matching document.

  • The first object identifies the student.

  • $set changes the specified field.

  • course is updated to Node.js.

After executing the command, MongoDB displays the update result.

To verify the change, run:

db.students.findOne({
    name: "Rahul Kumar"
})

You should now see the updated course information.

✦ 16. Update Multiple Documents Using updateMany()

If you want to update multiple student records with the same condition, use updateMany().

Example:

db.students.updateMany(
    {
        city: "Raipur"
    },
    {
        $set: {
            status: "Active"
        }
    }
)

This command updates the status of all matching students from Raipur to Active.

Difference between updateOne() and updateMany():

updateOne() updateMany()
Updates one matching document Updates all matching documents
Suitable for one record Suitable for multiple records
Stops after the first matching document Updates every matching document

Both methods are important for managing MongoDB documents.

✦ 17. Delete a Single Document Using deleteOne()

Sometimes you need to remove a particular student record from the database.

MongoDB provides the deleteOne() method.

Example:

db.students.deleteOne({
    name: "Rahul Kumar"
})

This command deletes the first document matching the specified condition.

MongoDB displays a result indicating how many documents were deleted.

To verify the deletion, run:

db.students.find({
    name: "Rahul Kumar"
})

If no matching document remains, the record has been deleted.

Important: Always verify your filter before executing a delete command.

✦ 18. Delete Multiple Documents Using deleteMany()

If you want to delete multiple documents matching a particular condition, use deleteMany().

Example:

db.students.deleteMany({
    status: "Inactive"
})

This command deletes all student documents where the status is Inactive.

To check the remaining records, execute:

db.students.find()

Difference:

  • deleteOne() deletes one matching document.

  • deleteMany() deletes all matching documents.

Be careful while using deleteMany() because it may remove multiple records.

✦ 19. Sort Documents Using sort()

MongoDB provides the sort() method to arrange documents according to a particular field.

For example, sort student records by age in ascending order:

db.students.find().sort({
    age: 1
})

To sort student records by age in descending order:

db.students.find().sort({
    age: -1
})

Explanation:

  • 1 represents ascending order.

  • -1 represents descending order.

Sorting helps organize database records according to your requirements.

✦ 20. Limit Documents Using limit()

Sometimes you only want to retrieve a specific number of documents.

MongoDB provides the limit() method.

Example:

db.students.find().limit(2)

This command displays only two documents.

You can also combine sorting and limiting:

db.students.find()
.sort({ age: -1 })
.limit(3)

This retrieves the three oldest student records according to the age field.

The limit() method is useful when working with large collections.

✦ 21. Count Documents Using countDocuments()

If you want to know how many student records are available in a collection, use countDocuments().

Example:

db.students.countDocuments()

This command returns the total number of documents in the students collection.

To count only active students, use:

db.students.countDocuments({
    status: "Active"
})

This displays the number of student records matching the specified condition.

✦ 22. Drop a Collection and Delete a Database

MongoDB also provides commands to remove collections and databases.

1. Drop a Collection

To delete the students collection, use:

db.students.drop()

This removes the entire collection and its documents.

2. Drop a Database

To delete the currently selected database, use:

db.dropDatabase()

This command removes the selected database.

Important: These operations can permanently remove data. Do not execute them on important databases without checking your selection and taking the required backup.

For learning purposes, use a test database only.

✦ 23. Connect MongoDB Atlas Using mongosh

Apart from connecting to a local MongoDB server, you can also use mongosh to connect to MongoDB Atlas.

MongoDB Atlas is a cloud-based database platform that allows developers to manage databases online.

Follow these steps:

Step 1: Open the official MongoDB Atlas website:

https://www.mongodb.com/atlas

Step 2: Sign in to your Atlas account.

Step 3: Open your database deployment.

Step 4: Click the Connect option.

Step 5: Select the MongoDB Shell connection method.

Step 6: Copy the connection command provided by Atlas.

The connection command will look similar to this:

mongosh "mongodb+srv://<cluster-address>/" --apiVersion 1 --username <username>

Step 7: Replace the placeholders using the actual details from your Atlas deployment.

Step 8: Execute the command in your terminal.

Step 9: Enter your database user's password when prompted, if requested.

If your credentials and network access settings are correct, mongosh will connect to your MongoDB Atlas deployment.

Security Tip: Never share your actual database username, password or connection string publicly.

✦ 24. Run JavaScript Commands in MongoDB Shell

MongoDB Shell is based on JavaScript, so you can execute JavaScript expressions and functions directly inside mongosh.

For example:

1. Display a Message

console.log("Welcome to MongoDB Shell");

2. Perform a Calculation

let a = 10;
let b = 20;

console.log(a + b);

3. Create a JavaScript Variable

let studentName = "Rahul Kumar";

console.log(studentName);

4. Create a JavaScript Function

function welcomeStudent(name) {
    return "Welcome " + name;
}

welcomeStudent("Rahul Kumar");

These examples demonstrate that mongosh supports JavaScript expressions and functions.

✦ 25. Run a JavaScript File Using mongosh

You can also execute MongoDB commands written inside a JavaScript file.

This is useful when you want to automate repetitive database operations.

Step 1: Create a new file named:

student.js

Step 2: Add the following code:

const database = db.getSiblingDB("college");

database.students.insertOne({
    name: "Amit Verma",
    age: 23,
    course: "MongoDB",
    city: "Raipur",
    status: "Active"
});

console.log("Student Record Inserted Successfully");

Step 3: Save the file.

Step 4: Open Command Prompt in the folder containing the file.

Step 5: Execute:

mongosh "mongodb://127.0.0.1:27017" student.js

This command connects to the local MongoDB server and executes the JavaScript file.

You should see the success message after the document is inserted.

Note: Make sure the local MongoDB server is running before executing the script.

✦ 26. Common MongoDB Shell Errors and Their Solutions

Beginners may face different problems while connecting to MongoDB using mongosh.

Here are some common errors and their solutions.

❖ mongosh Is Not Recognized

This error occurs when Windows cannot find the mongosh executable.

Solution: Verify the installation and check whether its installation directory is added to the system PATH.

❖ Connection Refused

This error may occur when the MongoDB server is not running or the connection address is incorrect.

Solution: Start MongoDB Community Server and verify the connection URI.

❖ Authentication Failed

This problem can occur when the database username or password is incorrect.

Solution: Verify the database credentials and authentication settings.

❖ IP Address Not Allowed

This error may occur when connecting to MongoDB Atlas from an IP address that is not permitted.

Solution: Add your current public IP address in the Atlas Network Access settings.

❖ Database Not Displaying

A newly selected database may not appear in the database list until data is stored or a collection is created.

Solution: Insert a document or create a collection, then run:

show dbs

❖ Incorrect Connection String

A wrong hostname, port, username or connection string can prevent a successful connection.

Solution: Verify the connection details and use the latest connection string from your MongoDB Atlas dashboard.

✦ 27. Practice Task: Create a Student Database Using mongosh

Now it is time to practise what you have learned.

Create a database named college and a collection named students using MongoDB Shell.

Required Student Fields:

  • Student Name

  • Age

  • Course

  • City

  • Mobile Number

  • Email

  • Status

Complete These Practical Tasks:

  1. Install MongoDB Shell on your computer.

  2. Check the mongosh version.

  3. Start your local MongoDB server.

  4. Connect to MongoDB using mongosh.

  5. Display all available databases.

  6. Create the college database.

  7. Create the students collection.

  8. Insert at least five student records.

  9. Retrieve all student records using find().

  10. Search for students from Raipur.

  11. Find students enrolled in MongoDB.

  12. Update one student's course.

  13. Change the status of a student.

  14. Sort student records by age.

  15. Display only three student records using limit().

  16. Count the total number of student records.

  17. Delete one sample student record.

  18. Connect to MongoDB Atlas using mongosh.

This practical exercise will help you understand how to manage MongoDB databases through command-line operations.

✦ Conclusion

MongoDB Shell (mongosh) is an important tool for developers who want to interact with MongoDB databases through commands. It provides a simple and powerful environment for executing database operations using JavaScript-based syntax.

In this tutorial, you learned how to download and install mongosh, connect to a local MongoDB server, understand basic commands, create databases and collections, insert documents, retrieve records, update information, delete documents and connect to MongoDB Atlas.

You also explored sorting, limiting, counting documents, executing JavaScript expressions and running external JavaScript files through MongoDB Shell.

At Param Classes, we believe that programming becomes easier when you learn concepts through practical examples. Keep practising these commands and gradually move towards advanced MongoDB concepts and real-world database projects.

Learn Today, Grow Tomorrow — Param Classes.

←
Post 8 of 35
→