MongoDB User Manual
Basic Concepts
Database
A database is the top-level container for data in MongoDB. Each database has its own collections and permission settings. You can create multiple databases in MongoDB, each independent of the others.
Collection
A collection is a group of MongoDB documents, similar to a table in a relational database. Documents in a collection can have different fields, making collections very flexible. Unlike relational databases, collections do not enforce a rigid, pre-defined schema.
Document
A document is the basic data unit in MongoDB, consisting of field and value pairs. Documents are similar to JSON objects and are stored using BSON (Binary JSON) format.
BSON is the binary representation of JSON documents, with additional data type support. The maximum document size is 16 MB.
Connect to MongoDB
Connect to Local Database Using mongosh
mongosh
Connect to Remote Database
mongosh "mongodb://hostname:port"
Connect Using Connection String with Authentication
mongosh "mongodb://username:password@hostname:port/database?authSource=admin"
Connect Using URI
mongosh "mongodb://localhost:27017,mongodb://localhost:27018/?replicaSet=myReplSet"
Database Operations
View Databases
show dbs
Switch/Create Database
use mydatabase
Note: When switching databases with the use command, if the database doesn't exist, MongoDB creates it, but it won't be truly created until you insert documents.
View Current Database Information
db.stats()
Drop Database
db.dropDatabase()
Collection Operations
View Collections
show collections
Create Collection
db.createCollection("mycollection")
Create Collection with Options
db.createCollection("mycollection", {
capped: true,
size: 1000000,
max: 100
})
Drop Collection
db.mycollection.drop()
View Collection Statistics
db.mycollection.stats()
Insert Documents
MongoDB provides the following methods to insert documents into a collection:
Insert a Single Document
db.users.insertOne({
name: "John",
age: 30,
email: "[email protected]",
address: {
city: "New York",
street: "Main Street"
},
hobbies: ["basketball", "swimming"]
})
Insert Multiple Documents
db.users.insertMany([
{ name: "Jane", age: 25, city: "Los Angeles" },
{ name: "Bob", age: 35, city: "Chicago" },
{ name: "Alice", age: 28, city: "San Francisco" }
])
Insert Document (Deprecated but Available)
db.users.insert({
name: "David",
age: 32
})
View Insert Result
# View inserted document ID
db.users.insertOne({ name: "Test" })
# Returns: { acknowledged: true, insertedId: ObjectId("...") }
Query Documents
Query All Documents
db.users.find()
This is equivalent to SELECT * FROM users in SQL.
Query a Single Document
db.users.findOne()
Query with Conditions
# Equality query
db.users.find({ age: 30 })
# Not equal query
db.users.find({ age: { $ne: 30 } })
# Greater than query
db.users.find({ age: { $gt: 25 } })
# Greater than or equal query
db.users.find({ age: { $gte: 25 } })
# Less than query
db.users.find({ age: { $lt: 30 } })
# Less than or equal query
db.users.find({ age: { $lte: 30 } })
# Range query
db.users.find({ age: { $gte: 20, $lte: 30 } })
Logical Operators
# AND (default)
db.users.find({ age: { $gte: 25 }, name: "Jane" })
# OR
db.users.find({ $or: [{ age: { $gte: 30 } }, { name: "Bob" }] })
# NOR (neither nor)
db.users.find({ $nor: [{ age: { $lt: 20 } }, { city: "New York" }] })
# NOT
db.users.find({ age: { $not: { $gte: 25 } } })
Array Queries
# Array contains element
db.users.find({ hobbies: "basketball" })
# Array contains all elements
db.users.find({ hobbies: { $all: ["basketball", "swimming"] } })
# Array length
db.users.find({ hobbies: { $size: 2 } })
# Array element at specific position
db.users.find({ "hobbies.0": "basketball" })
# Array element matching condition
db.users.find({ hobbies: { $elemMatch: { $eq: "basketball" } } })
Nested Document Queries
# Nested document field query
db.users.find({ "address.city": "New York" })
# Complete nested document match
db.users.find({ address: { city: "New York", street: "Main Street" } })
Projection (Return Specified Fields Only)
# Return only name and email fields
db.users.find({ age: 30 }, { name: 1, email: 1 })
# Exclude a field
db.users.find({}, { age: 0 })
# Return all fields except _id
db.users.find({}, { _id: 0 })
Sort
# Sort by age ascending
db.users.find().sort({ age: 1 })
# Sort by age descending
db.users.find().sort({ age: -1 })
# Multi-field sort
db.users.find().sort({ age: -1, name: 1 })
Limit and Skip
# Return first 5 documents
db.users.find().limit(5)
# Skip first 10 documents, return next 5 (pagination)
db.users.find().skip(10).limit(5)
# Count documents
db.users.countDocuments({ age: { $gte: 25 } })
# Estimate collection document count (fast but may be inaccurate)
db.users.estimatedDocumentCount()
Cursor Operations
# Use cursor
var cursor = db.users.find()
while (cursor.hasNext()) {
printjson(cursor.next())
}
# forEach iteration
db.users.find().forEach(function(doc) {
print("Name: " + doc.name)
})
Update Documents
Update a Single Document
db.users.updateOne(
{ name: "John" },
{ $set: { age: 31 } }
)
Update Multiple Documents
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
Replace a Document
db.users.replaceOne(
{ name: "John" },
{ name: "John", age: 32, email: "[email protected]", city: "Boston" }
)
Update Operators
# $set - Set field value
db.users.updateOne({ name: "Jane" }, { $set: { age: 26 } })
# $unset - Remove field
db.users.updateOne({ name: "Jane" }, { $unset: { email: "" } })
# $inc - Increment/decrement
db.users.updateOne({ name: "Jane" }, { $inc: { age: 1 } })
db.users.updateOne({ name: "Jane" }, { $inc: { age: -1 } })
# $rename - Rename field
db.users.updateOne({ name: "Jane" }, { $rename: { "name": "fullname" } })
# $mul - Multiply
db.users.updateOne({ name: "Jane" }, { $mul: { age: 2 } })
# $min - Set minimum value
db.users.updateOne({ name: "Jane" }, { $min: { age: 20 } })
# $max - Set maximum value
db.users.updateOne({ name: "Jane" }, { $max: { age: 40 } })
# $push - Add element to array
db.users.updateOne({ name: "Jane" }, { $push: { hobbies: "running" } })
# $pull - Remove matching elements from array
db.users.updateOne({ name: "Jane" }, { $pull: { hobbies: "swimming" } })
# $addToSet - Add element to array (no duplicates)
db.users.updateOne({ name: "Jane" }, { $addToSet: { hobbies: "basketball" } })
# $pop - Remove first or last element from array
db.users.updateOne({ name: "Jane" }, { $pop: { hobbies: 1 } })
Upsert Operation
# Insert if not exists, update if exists
db.users.updateOne(
{ name: "New User" },
{ $set: { age: 25, city: "Seattle" } },
{ upsert: true }
)
Delete Documents
Delete a Single Document
db.users.deleteOne({ name: "John" })
Delete Multiple Documents
db.users.deleteMany({ age: { $lt: 20 } })
Delete All Documents
db.users.deleteMany({})
Aggregation Pipeline
The aggregation pipeline is one of MongoDB's most powerful features, used to process data streams and perform complex data transformations and analysis.
Basic Syntax
db.collection.aggregate([
{ $stage1: { ... } },
{ $stage2: { ... } },
...
])
Common Aggregation Stages
$match - Filter Documents
db.users.aggregate([
{ $match: { age: { $gte: 25 } } }
])
$project - Projection
db.users.aggregate([
{ $project: { _id: 0, name: 1, age: 1 } }
])
$group - Group
# Count users by age
db.users.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
# Calculate average age
db.users.aggregate([
{ $group: { _id: null, avgAge: { $avg: "$age" } } }
])
# Group and collect names
db.users.aggregate([
{ $group: { _id: "$city", users: { $push: "$name" } } }
])
$sort - Sort
db.users.aggregate([
{ $sort: { age: -1, name: 1 } }
])
$limit - Limit Number
db.users.aggregate([
{ $limit: 5 }
])
$skip - Skip Documents
db.users.aggregate([
{ $skip: 10 },
{ $limit: 5 }
])
$unwind - Deconstruct Array
db.users.aggregate([
{ $unwind: "$hobbies" }
])
$lookup - Join Collections
# Assuming two collections: orders and products
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "productDetails"
}
}
])
Aggregation Operators
Arithmetic Operators
db.sales.aggregate([
{
$project: {
total: { $add: ["$price", "$tax"] },
discount: { $multiply: ["$price", 0.1] }
}
}
])
String Operators
db.users.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
upperName: { $toUpper: "$name" }
}
}
])
Date Operators
db.users.aggregate([
{
$project: {
year: { $year: "$birthdate" },
month: { $month: "$birthdate" },
day: { $dayOfMonth: "$birthdate" }
}
}
])
Complete Example
# Find the top three airlines with the most direct flights out of PDX
db.routes.aggregate([
{
$match: {
"src_airport": "PDX",
"stops": 0
}
},
{
$group: {
_id: "$airline.name",
count: { $sum: 1 }
}
},
{
$sort: { count: -1 }
},
{
$limit: 3
}
])
Indexes
Indexes support efficient execution of queries in MongoDB. Without indexes, MongoDB must scan every document in a collection to return query results.
Create Indexes
# Single field index
db.users.createIndex({ name: 1 })
# Descending index
db.users.createIndex({ age: -1 })
# Compound index
db.users.createIndex({ age: 1, name: 1 })
# Unique index
db.users.createIndex({ email: 1 }, { unique: true })
# Text index
db.users.createIndex({ description: "text" })
# Multikey index (array field)
db.users.createIndex({ hobbies: 1 })
# Geospatial index
db.locations.createIndex({ location: "2dsphere" })
# Hashed index
db.users.createIndex({ _id: "hashed" })
View Indexes
# View all indexes on a collection
db.users.getIndexes()
# View index size
db.users.totalIndexSize()
Drop Indexes
# Drop specified index
db.users.dropIndex("name_1")
# Drop all indexes (except _id index)
db.users.dropIndexes()
# Drop text index
db.users.dropIndex("description_text")
Index Properties
# Sparse index (only indexes non-null values)
db.users.createIndex({ email: 1 }, { sparse: true })
# Partial index
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { email: { $exists: true } } }
)
# TTL index (automatic expiration)
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
Indexing Strategy Recommendations
- Create indexes on fields frequently used in query conditions
- Field order in compound indexes matters: place exact match fields first, range query fields last
- Avoid creating too many indexes on collections with high write frequency
- Use explain() to analyze query performance
Query Analysis
# Analyze query
db.users.find({ age: 25 }).explain()
# Analyze execution plan
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).explain("executionStats")
Replica Set Operations
A replica set is a group of MongoDB instances that maintain the same data set, providing redundancy and high availability.
Initialize Replica Set
rs.initiate()
View Replica Set Status
rs.status()
View Replica Set Configuration
rs.conf()
Add Secondary Member
rs.add("hostname:27017")
Add Arbiter
rs.addArb("hostname:27017")
Remove Member
rs.remove("hostname:27017")
Replica Set Elections
When the primary is unavailable, the replica set automatically conducts an election. You can trigger an election with:
# Force current node to become primary (use in specific situations)
rs.stepDown()
Read Preference
# Read from primary (default)
db.getMongo().setReadPref("primary")
# Read from secondary
db.getMongo().setReadPref("secondary")
# Read from nearest node
db.getMongo().setReadPref("nearest")
Sharding Operations
Sharding is MongoDB's approach to horizontal scaling, distributing data across multiple servers.
Enable Sharding
sh.enableSharding("mydatabase")
Shard a Collection
sh.shardCollection("mydatabase.mycollection", { _id: 1 })
View Sharding Status
sh.status()
Add Shard
sh.addShard("shard_replica_set/hostname:27017")
Data Import and Export
Using mongodump and mongorestore
Export Data
# Export entire database
mongodump --db=mydatabase --out=/backup
# Export specific collection
mongodump --db=mydatabase --collection=users --out=/backup
# Export with compression
mongodump --db=mydatabase --gzip --out=/backup
Import Data
# Restore entire database
mongorestore --db=mydatabase /backup/mydatabase
# Restore specific collection
mongorestore --db=mydatabase --collection=users /backup/mydatabase/users.bson
# Restore with compression
mongorestore --db=mydatabase --gzip /backup/mongodb
Using mongoexport and mongoimport
Export as JSON
# Export as JSON
mongoexport --db=mydatabase --collection=users --out=users.json
# Export as JSON array
mongoexport --db=mydatabase --collection=users --out=users.json --jsonArray
# Export CSV
mongoexport --db=mydatabase --collection=users --out=users.csv --fields=name,age,email
Import from JSON
# Import from JSON
mongoimport --db=mydatabase --collection=users --file=users.json
# Import from JSON array
mongoimport --db=mydatabase --collection=users --file=users.json --jsonArray
# Import from CSV
mongoimport --db=mydatabase --collection=users --file=users.csv --headerline
Common Administrative Commands
View Server Status
db.serverStatus()
View Current Database Status
db.stats()
View Collection Statistics
db.users.stats()
View Current Operations
db.currentOp()
View Slow Queries
# View recent slow queries
db.system.profile.find().sort({ ts: -1 }).limit(10)
Force Shutdown Database
# Use in emergencies only
db.adminCommand({ shutdown: 1 })
Transaction Operations
MongoDB 4.0+ supports multi-document transactions.
Basic Transaction
session = db.getMongo().startSession()
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })
try {
session.getDatabase("mydb").accounts.updateOne(
{ accountId: 1 },
{ $inc: { balance: -100 } }
)
session.getDatabase("mydb").accounts.updateOne(
{ accountId: 2 },
{ $inc: { balance: 100 } }
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
} finally {
session.endSession()
}
Change Streams
Change streams allow applications to listen to data changes in real time.
# Listen for collection changes
var changeStream = db.users.watch()
while (changeStream.hasNext()) {
printjson(changeStream.next())
}
GridFS
GridFS is used to store large files exceeding the 16 MB limit.
# Upload file
mongofiles put myfile.txt
# List files
mongofiles list
# Download file
mongofiles get myfile.txt
# Delete file
mongofiles delete myfile.txt
