Mastering MongoDB Shell Commands: A Comprehensive Guide with Examples

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.

MongoDB Shell (mongosh) is an interactive JavaScript interface used to interact with MongoDB instances. It allows users to perform various operations like querying, updating data, and managing databases directly from the command line.

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>

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!

Write a Reply or Comment

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