MongoDB Shell (mongosh)
The MongoDB Shell, often referred to as "mongosh", is a powerful command-line interface that allows you to interact with your MongoDB databases. It's an essential tool for MongoDB administrators and developers, enabling you to create, read, update, and delete data, manage your database, and run administrative commands.
What is MongoDB Shell?
MongoDB Shell is an interactive JavaScript interface to MongoDB that allows you to:
- Query and manipulate data
- Perform administrative operations
- Test queries and aggregation pipelines
- Prototype JavaScript applications
- Manage database users and their permissions
- Monitor database performance
Getting Started with MongoDB Shell
Connecting to MongoDB
To start the MongoDB Shell, open your terminal or command prompt and enter:
mongosh
This command will connect you to a MongoDB instance running on the default host (localhost
) and port (27017
).
If you need to connect to a specific MongoDB deployment, you can specify the connection string:
mongosh "mongodb://hostname:port/database"
Example with authentication:
mongosh "mongodb://username:password@hostname:port/database"
When successfully connected, you'll see output similar to:
Current Mongosh Log ID: 64a7e8f9a953c7c12345abcd
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.1
Using MongoDB: 6.0.6
Using Mongosh: 1.10.1
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
------
The server generated these startup warnings when booting
2023-07-07T10:15:19.631+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
------
test>
Basic Navigation
Once connected, you're placed in the test
database by default. Here are some basic navigation commands:
- Show all available databases:
show dbs
Output:
admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB
- Switch to a specific database:
use myDatabase
Output:
switched to db myDatabase
- Show collections in the current database:
show collections
Output (example):
users
products
orders
CRUD Operations in MongoDB Shell
Create (Insert) Documents
To insert a single document into a collection:
db.users.insertOne({
name: "John Doe",
email: "[email protected]",
age: 30,
createdAt: new Date()
})
Output:
{
acknowledged: true,
insertedId: ObjectId("64a7e9f9a953c7c12345abce")
}
To insert multiple documents at once:
db.users.insertMany([
{
name: "Jane Smith",
email: "[email protected]",
age: 28,
createdAt: new Date()
},
{
name: "Bob Johnson",
email: "[email protected]",
age: 35,
createdAt: new Date()
}
])
Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64a7e9f9a953c7c12345abcf"),
'1': ObjectId("64a7e9f9a953c7c12345abd0")
}
}
Read (Query) Documents
To find all documents in a collection:
db.users.find()
Output:
[
{
_id: ObjectId("64a7e9f9a953c7c12345abce"),
name: 'John Doe',
email: '[email protected]',
age: 30,
createdAt: ISODate("2023-07-07T10:20:09.321Z")
},
{
_id: ObjectId("64a7e9f9a953c7c12345abcf"),
name: 'Jane Smith',
email: '[email protected]',
age: 28,
createdAt: ISODate("2023-07-07T10:20:09.321Z")
},
{
_id: ObjectId("64a7e9f9a953c7c12345abd0"),
name: 'Bob Johnson',
email: '[email protected]',
age: 35,
createdAt: ISODate("2023-07-07T10:20:09.321Z")
}
]
To find documents matching specific criteria:
db.users.find({ age: { $gt: 30 } })
Output:
[
{
_id: ObjectId("64a7e9f9a953c7c12345abd0"),
name: 'Bob Johnson',
email: '[email protected]',
age: 35,
createdAt: ISODate("2023-07-07T10:20:09.321Z")
}
]
To find a single document:
db.users.findOne({ name: "Jane Smith" })
Output:
{
_id: ObjectId("64a7e9f9a953c7c12345abcf"),
name: 'Jane Smith',
email: '[email protected]',
age: 28,
createdAt: ISODate("2023-07-07T10:20:09.321Z")
}
Update Documents
To update a single document:
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31, updatedAt: new Date() } }
)
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
To update multiple documents:
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Delete Documents
To delete a single document:
db.users.deleteOne({ name: "Bob Johnson" })
Output:
{ acknowledged: true, deletedCount: 1 }
To delete multiple documents:
db.users.deleteMany({ age: { $lt: 30 } })
Output:
{ acknowledged: true, deletedCount: 1 }
Advanced MongoDB Shell Operations
Querying with Projection
You can specify which fields to include or exclude in the results:
// Include only name and email fields
db.users.find({}, { name: 1, email: 1, _id: 0 })
Output:
[
{ name: 'John Doe', email: '[email protected]' }
]
Sorting Results
To sort query results:
// Sort by age in descending order
db.users.find().sort({ age: -1 })
Output:
[
{
_id: ObjectId("64a7e9f9a953c7c12345abce"),
name: 'John Doe',
email: '[email protected]',
age: 31,
createdAt: ISODate("2023-07-07T10:20:09.321Z"),
updatedAt: ISODate("2023-07-07T10:25:12.456Z")
}
]
Limiting Results
To limit the number of results:
db.users.find().limit(2)
Counting Documents
To count documents in a collection:
db.users.countDocuments({ age: { $gt: 30 } })
Output:
1
Aggregation Pipeline
MongoDB's aggregation pipeline is a powerful feature for data processing:
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } },
{ $limit: 3 }
])
This pipeline:
- Matches only completed orders
- Groups them by customer ID
- Calculates the total amount spent per customer
- Sorts customers by total spent (descending)
- Returns only the top 3 customers
MongoDB Shell Configuration
Customizing the Prompt
You can customize your MongoDB Shell prompt by adding this to your .mongoshrc.js
file:
prompt = function() {
return `${db.getName()}@${new Date().toLocaleTimeString()} > `;
};
Creating Helper Functions
You can create custom helper functions in your .mongoshrc.js
file:
// Function to find recent documents
findRecent = function(collection, minutes = 60) {
const cutoffTime = new Date(Date.now() - minutes * 60 * 1000);
return db[collection].find({ createdAt: { $gt: cutoffTime } });
};
Usage:
findRecent("users", 30) // Find users created in the last 30 minutes
Real-world Examples
Example 1: Managing an E-commerce Product Catalog
// Create a products collection with validation
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price", "category"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
price: {
bsonType: "number",
minimum: 0,
description: "must be a positive number and is required"
},
category: {
bsonType: "string",
description: "must be a string and is required"
},
inStock: {
bsonType: "bool",
description: "must be a boolean"
}
}
}
}
})
// Add products
db.products.insertMany([
{
name: "Smartphone X",
price: 799.99,
category: "Electronics",
inStock: true,
features: ["5G", "4K Camera", "Water Resistant"]
},
{
name: "Coffee Maker Pro",
price: 129.99,
category: "Kitchen",
inStock: true,
features: ["Programmable", "Thermal Carafe"]
},
{
name: "Running Shoes",
price: 89.99,
category: "Sportswear",
inStock: false,
features: ["Lightweight", "Breathable"]
}
])
// Find products that are in stock and cost less than $100
db.products.find({
inStock: true,
price: { $lt: 100 }
})
// Find the average price by category
db.products.aggregate([
{ $group: { _id: "$category", avgPrice: { $avg: "$price" } } }
])
Example 2: Analyzing User Activity
// Insert some user activity logs
db.userActivity.insertMany([
{ userId: "user123", action: "login", timestamp: new Date("2023-07-01T08:30:00Z"), device: "mobile" },
{ userId: "user123", action: "view_product", productId: "prod456", timestamp: new Date("2023-07-01T08:35:00Z"), device: "mobile" },
{ userId: "user123", action: "add_to_cart", productId: "prod456", timestamp: new Date("2023-07-01T08:40:00Z"), device: "mobile" },
{ userId: "user123", action: "checkout", amount: 79.99, timestamp: new Date("2023-07-01T08:45:00Z"), device: "mobile" },
{ userId: "user456", action: "login", timestamp: new Date("2023-07-01T10:15:00Z"), device: "desktop" },
{ userId: "user456", action: "view_product", productId: "prod789", timestamp: new Date("2023-07-01T10:20:00Z"), device: "desktop" },
{ userId: "user456", action: "logout", timestamp: new Date("2023-07-01T10:25:00Z"), device: "desktop" }
])
// Find a user's journey (all actions by a specific user)
db.userActivity.find({ userId: "user123" }).sort({ timestamp: 1 })
// Count actions by device type
db.userActivity.aggregate([
{ $group: { _id: "$device", count: { $sum: 1 } } }
])
// Calculate conversion rate from view_product to checkout
db.userActivity.aggregate([
{ $match: { action: { $in: ["view_product", "checkout"] } } },
{ $group: {
_id: "$action",
count: { $sum: 1 }
}
}
])
Database Administration Tasks
Creating an Index
Indexes can dramatically improve query performance:
// Create an index on the email field
db.users.createIndex({ email: 1 }, { unique: true })
Output:
'email_1'
Getting Collection Statistics
db.users.stats()
Output:
{
ns: 'myDatabase.users',
size: 1234,
count: 1,
avgObjSize: 1234,
storageSize: 20480,
/* ... other statistics ... */
}
Managing Users
Creating a new user:
db.createUser({
user: "appUser",
pwd: "securePassword123",
roles: [{ role: "readWrite", db: "myDatabase" }]
})
Tips for Working with MongoDB Shell
Using Pretty Output
To make JSON output more readable:
db.users.find().pretty()
Saving Query Results to Variables
You can save results to variables for further processing:
let activeUsers = db.users.find({ active: true }).toArray()
print(`Found ${activeUsers.length} active users`)
activeUsers.forEach(user => print(user.name))
Writing Multi-line Commands
For complex queries, you can write them over multiple lines:
db.products.find({
category: "Electronics",
price: { $gt: 500 },
inStock: true
})
Summary
The MongoDB Shell (mongosh) is a powerful tool for interacting with MongoDB databases. It allows you to:
- Connect to MongoDB databases locally or remotely
- Perform CRUD operations on collections and documents
- Run complex queries and aggregations
- Create and manage indexes
- Perform administrative tasks
- Test and prototype database interactions
With the commands and techniques covered in this guide, you now have a solid foundation for working with the MongoDB Shell in your projects. Remember that MongoDB is a flexible NoSQL database that allows you to store and query data in ways that can be more intuitive and faster for many applications compared to traditional relational databases.
Practice Exercises
-
Connect to a MongoDB database and create a new collection called "library" with books that include title, author, publication year, and genre fields.
-
Write a query to find all books published after 2010 by a specific author.
-
Create an index on the fields that would best optimize the query from exercise 2.
-
Write an aggregation pipeline that groups books by genre and calculates the average publication year per genre.
-
Create a complex document with nested arrays and objects, then practice querying for specific nested elements.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)