MongoDB Shell

Master the MongoDB command-line interface

💻 MongoDB Shell (mongosh)

The MongoDB Shell is an interactive JavaScript interface for MongoDB. Use it to query data, perform administrative operations, and test database commands directly from your terminal.


# Start MongoDB Shell
mongosh
                                    

Output:

Current Mongosh Log ID: 6a7b8c9d0e1f2a3b4c5d6e7f
Connecting to: mongodb://127.0.0.1:27017
Using MongoDB: 7.0.0
test>

Shell Basics

Learn essential MongoDB Shell commands for connecting, navigating databases, and performing basic operations. The shell provides a powerful JavaScript environment for interacting with your MongoDB databases.

🔌

Connect

Connect to MongoDB instances

mongosh
🗄️

Databases

Create and switch databases

use myDB
📝

Commands

Execute database operations

db.users.find()

Help

Get command assistance

help

🔹 Connecting to MongoDB

Different ways to connect to MongoDB using the shell:

🔸 Local Connection

# Connect to local MongoDB (default)
mongosh

# Connect to specific host and port
mongosh "mongodb://localhost:27017"

# Connect to specific database
mongosh "mongodb://localhost:27017/myDatabase"

🔸 Remote Connection

# Connect to remote server
mongosh "mongodb://192.168.1.100:27017"

# Connect with authentication
mongosh "mongodb://username:password@localhost:27017"

# Connect to MongoDB Atlas
mongosh "mongodb+srv://cluster0.mongodb.net/myDatabase" --username myUser

Output:

Enter password: ****
Current Mongosh Log ID: 6a7b8c9d0e1f2a3b4c5d6e7f
Connecting to: mongodb+srv://cluster0.mongodb.net/myDatabase
Using MongoDB: 7.0.0
myDatabase>

🔹 Basic Shell Commands

Essential commands for navigating and managing databases:

// Show all databases
show dbs

// Switch to database (creates if doesn't exist)
use myDatabase

// Show current database
db

// Show all collections in current database
show collections

// Get MongoDB version
db.version()

// Get server status
db.serverStatus()

// Exit shell
exit

Output:

admin       0.000GB
config      0.000GB
local       0.000GB
myDatabase  0.001GB

switched to db myDatabase

myDatabase

users
products
orders

7.0.0

🔹 Database Operations

Create, view, and manage databases from the shell:

// Create/switch to database
use shopDB

// Insert data (creates database if it doesn't exist)
db.products.insertOne({ name: "Laptop", price: 999 })

// View current database
db.getName()

// Get database statistics
db.stats()

// Drop current database
db.dropDatabase()

// List all databases with details
db.adminCommand({ listDatabases: 1 })

Output:

switched to db shopDB
{ acknowledged: true, insertedId: ObjectId("...") }
shopDB
{
  db: "shopDB",
  collections: 1,
  views: 0,
  objects: 1,
  dataSize: 128
}
{ ok: 1, dropped: "shopDB" }

🔹 Collection Operations

Work with collections using shell commands:

// Show all collections
show collections

// Create collection explicitly
db.createCollection("customers")

// Get collection statistics
db.customers.stats()

// Rename collection
db.customers.renameCollection("clients")

// Drop collection
db.clients.drop()

// List all collections with details
db.getCollectionNames()

Output:

products
orders
customers

{ ok: 1 }

{
  ns: "shopDB.customers",
  count: 0,
  size: 0
}

{ ok: 1 }
true

[ "products", "orders", "clients" ]

🔹 Help Commands

Get assistance and documentation within the shell:

// General help
help

// Database methods help
db.help()

// Collection methods help
db.collection.help()

// Specific method help
db.collection.find.help()

// Show available commands
show

// List all helper methods
db.listCommands()

Output:

Shell Help:
  use                Set current database
  show               'show databases'/'show collections'
  exit               Quit the MongoDB shell

Database Methods:
  db.collection.find()     Find documents
  db.collection.insertOne() Insert a document
  db.collection.updateOne() Update a document

🔹 Shell Variables and JavaScript

Use JavaScript features within the MongoDB Shell:

// Store query results in variable
var users = db.users.find().toArray()

// Loop through results
users.forEach(function(user) {
    print(user.name)
})

// Use JavaScript functions
var count = db.products.countDocuments()
print("Total products: " + count)

// Multi-line commands
var newUser = {
    name: "Alice",
    email: "[email protected]",
    age: 28
}
db.users.insertOne(newUser)

// Date operations
var today = new Date()
db.logs.insertOne({ message: "Login", timestamp: today })

Output:

John
Alice
Bob
Total products: 15
{ acknowledged: true, insertedId: ObjectId("...") }
{ acknowledged: true, insertedId: ObjectId("...") }

🔹 Shell Configuration

Customize your MongoDB Shell experience:

🔸 Shell Options

# Quiet mode (less output)
mongosh --quiet

# Evaluate JavaScript
mongosh --eval "db.users.find()"

# Execute JavaScript file
mongosh myScript.js

# No automatic connection
mongosh --nodb

🔸 Configuration File

// Create ~/.mongoshrc.js for custom settings
// This runs every time mongosh starts

// Custom prompt
prompt = function() {
    return db + "> ";
}

// Custom helper function
function showCollections() {
    return db.getCollectionNames();
}

// Set display options
config.set("displayBatchSize", 10)

🔹 Useful Shell Shortcuts

Keyboard shortcuts to improve productivity:

Shortcut Action
Ctrl + C Cancel current operation
Ctrl + D Exit shell
Up/Down Arrow Navigate command history
Tab Auto-complete commands
Ctrl + L Clear screen

🔹 Running Shell Scripts

Execute JavaScript files with MongoDB commands:

🔸 Create Script File (seed.js)

// seed.js - Populate database with sample data
use shopDB

db.products.insertMany([
    { name: "Laptop", price: 999, category: "Electronics" },
    { name: "Mouse", price: 25, category: "Accessories" },
    { name: "Keyboard", price: 75, category: "Accessories" }
])

print("Database seeded successfully!")
print("Total products: " + db.products.countDocuments())

🔸 Execute Script

# Run script from command line
mongosh seed.js

# Run script from within shell
load("seed.js")

# Run with specific connection
mongosh "mongodb://localhost:27017/shopDB" seed.js

Output:

switched to db shopDB
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("..."),
    '2': ObjectId("...")
  }
}
Database seeded successfully!
Total products: 3

🧠 Test Your Knowledge

Which command shows all databases in MongoDB Shell?