MongoDB Shell Commands in 2026: Complete Helpful Guide with Examples

Mastering MongoDB Shell Commands

This guide provides an in-depth overview of commonly used MongoDB shell commands, categorized by their functions, with examples and summaries to ensure clarity.

The MongoDB Shell, also known as mongosh, is an interactive JavaScript-based command-line interface that allows developers and database administrators to communicate directly with MongoDB databases.

Using MongoDB shell commands, you can create databases, manage collections, insert and query documents, perform aggregation operations, create indexes, manage users, monitor performance, and execute administrative tasks.

This updated 2026 guide covers the most commonly used MongoDB shell commands with syntax, explanations, practical examples, and summaries to help beginners and experienced developers efficiently manage MongoDB databases.

What is MongoDB Shell (mongosh)?

mongosh is the modern MongoDB shell introduced as the replacement for the legacy mongo shell. It provides:

  • Interactive JavaScript environment
  • Improved syntax highlighting
  • Better error messages
  • Enhanced command history
  • Native support for modern MongoDB features
  • Integration with MongoDB Atlas
  • Better developer experience

The shell allows you to:

  • Connect to local or cloud databases
  • Run CRUD operations
  • Create indexes
  • Execute aggregation pipelines
  • Manage users and permissions
  • Monitor database performance
  • Administer MongoDB servers

Official MongoDB Shell Documentation:

MongoDB Shell Documentation

Prerequisites

Before diving into the MongoDB shell commands, ensure you have:

  1. MongoDB Installed: Download and install MongoDB from the official MongoDB website.
  2. MongoDB Shell (mongosh): Use the MongoDB Shell (mongosh), which is included in MongoDB installations starting from version 5.0.

To connect to your MongoDB instance, open a terminal and type:

mongosh

If you’re connecting to a specific MongoDB instance or cluster, use:

mongosh "mongodb+srv://<cluster-url>"

Replace with the connection string for your MongoDB deployment.

List of MongoDB Shell Commands

The MongoDB shell is an interactive JavaScript interface to MongoDB, which allows users to insert new objects into the database, query the existing collections, and perform administrative tasks for managing the database, its data, and its users.

See below for list MongoDB Shell commands:

1. Database Operations

These Mongodb shell commands help you manage and switch databases.

a. List Databases

show dbs

Lists all databases along with their sizes. Example:

admin 0.000GB
config 0.001GB
local 0.000GB

Use this command to view available databases on your server.

The operation corresponds to the listDatabases command. If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.

b. Switch Database

To switch databases, issue the use <db> helper, as in the following example:

use <database_name>

Switches to the specified database. If it doesn’t exist, it will be created once data is added.

c. Drop Database

Deletes the currently selected database.

db.dropDatabase()

Example:

use testDatabase
db.dropDatabase()

Removes a database and all its collections permanently.

d. View Database Statistics

db.stats()

Displays statistics about the current database, such as the number of collections, storage size, and indexes. Example output:

{
"db": "test",
"collections": 5,
"views": 0,
"objects": 250,
"avgObjSize": 120,
"dataSize": 30000,
"indexes": 5,
"indexSize": 4096
}

Provides an overview of the database’s structure and storage.


2. Collection Operations

Collections in MongoDB are analogous to tables in relational databases.

a. List Collections

show collections

Displays all collections in the current database.

Useful for verifying the collections available in the active database.

b. Create Collection

db.createCollection("collection_name")

Creates a new collection.

Example:

db.createCollection("inventory")

While MongoDB creates collections automatically when data is inserted, this command allows manual creation with options for validation rules.

c. Drop Collection

db.collection_name.drop()

Removes the specified collection.

Example

db.inventory.drop()

Removes the collection permanently. Use it cautiously to avoid data loss.


3. CRUD Operations

a. Insert Documents

Insert single or multiple documents into a collection.

  • Single Document:
    db.collection_name.insertOne({ key: "value" })
    
  • Multiple Documents:
    db.collection_name.insertMany([{ key1: "value1" }, { key2: "value2" }])
    

b. Read Documents

Retrieve documents from a collection.

  • Find All:
    db.collection_name.find()
    
  • Find with Query:
    db.collection_name.find({ key: "value" })
    
  • Formatted Output:
    db.collection_name.find().pretty()
    

c. Update Documents

Modify existing documents.

  • Update One:
    db.collection_name.updateOne(
    { key: "value" },
    { $set: { key: "new_value" } }
    )
    
  • Update Many:
    db.collection_name.updateMany(
    { key: "value" },
    { $set: { key: "new_value" } }
    )
    

d. Delete Documents

Remove documents from a collection.

  • Delete One:
    db.collection_name.deleteOne({ key: "value" })
    
  • Delete Many:
    db.collection_name.deleteMany({ key: "value" })
    

4. Indexing

Indexes improve query performance.

a. Create Index

Indexes improve query performance by organizing documents efficiently. Use 1 for ascending or -1 for descending.

db.collection_name.createIndex({ key: 1 })

Creates an ascending index on the specified field.

b. View Indexes

db.collection_name.getIndexes()

c. Drop Index

Removes a specific index from a collection.

db.collection_name.dropIndex("index_name")

5. Aggregation

Aggregation frameworks allow you to process and analyze data.

a. Basic Aggregation Pipeline

db.collection_name.aggregate([
{ $match: { key: "value" } },
{ $group: { _id: "$group_field", total: { $sum: "$numeric_field" } } }
])
Processes data through a pipeline of stages such as $match, $group, and $sort.

6. Administrative Mongodb Shell Commands

a. View Current Operations

db.currentOp()

Shows currently running operations.

b. Kill a Process

db.killOp(<operation_id>)

Terminates the specified operation.

c. Server Status

db.serverStatus()

Provides comprehensive details about the database server, such as uptime, memory usage, and connections.

d. Storage Statistics

Provides a detailed report about a collection, including document count, storage size, and index usage. This helps optimize performance and storage.

db.collection_name.stats()

Displays storage statistics for a specific collection, including document count, index sizes, and allocated storage.


7. User Management

a. Create User

db.createUser({
user: "username",
pwd: "password",
roles: [{ role: "readWrite", db: "database_name" }]
})

b. Remove User

db.dropUser("username")

8. Backup and Restore

a. Export Data

mongodump --db=<database_name> --out=<output_directory>

b. Import Data

mongorestore --db=<database_name> <input_directory>

Best Practices for MongoDB Shell Usage in 2026

1. Use Indexes Properly

Indexes improve query speed dramatically but consume additional storage.

2. Avoid Unbounded Queries

Always filter large datasets to improve performance.

3. Use Aggregation Efficiently

Optimize aggregation pipelines using $match early in the pipeline.

4. Enable Authentication

Always secure production databases with authentication and role-based access control.

5. Use Backups Regularly

Schedule automatic backups for production systems.

6. Monitor Database Performance

Use:

  • db.serverStatus()
  • db.stats()
  • db.collection.stats()

to monitor database health.


Advantages of MongoDB Shell

  • Easy command-line interaction
  • JavaScript-based syntax
  • Fast database management
  • Powerful aggregation support
  • Flexible querying
  • Ideal for developers and administrators
  • Supports cloud and local deployments

Disadvantages of MongoDB Shell

  • Command-line learning curve for beginners
  • Risk of accidental data deletion
  • Requires careful permission management
  • Complex aggregation pipelines can become difficult to maintain

Credits

Reference:

Conclusion

MongoDB Shell commands provide powerful tools for database management, ranging from basic CRUD operations to advanced administrative tasks. By mastering these Mongodb shell commands, you can efficiently interact with and manage MongoDB databases.

Let us know if you’d like deeper insights into any specific MongoDB shell commands or advanced use cases!

By mastering these MongoDB shell commands, you can efficiently build, maintain, troubleshoot, and optimize MongoDB-powered applications. As MongoDB continues evolving with cloud-native features, AI integrations, and scalable architectures, understanding the MongoDB shell remains an important skill for modern developers.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *