| name | mongodb |
| description | MongoDB fundamentals including document model, CRUD operations, querying, indexing, and aggregation framework for NoSQL database applications. |
| sasmp_version | 1.3.0 |
| bonded_agent | 03-mongodb |
| bond_type | PRIMARY_BOND |
MongoDB Mastery
Document Model Basics
{
_id: ObjectId("507f1f77bcf86cd799439011"),
firstName: "John",
lastName: "Doe",
email: "john@example.com",
salary: 75000,
department: "Engineering",
skills: ["JavaScript", "Python", "SQL"],
address: {
street: "123 Main St",
city: "New York",
state: "NY"
},
joinDate: new Date("2023-01-15")
}
Collection Operations
use company_db
db.employees.insertOne({
firstName: "Jane",
lastName: "Smith",
email: "jane@example.com",
salary: 80000
})
db.employees.insertMany([
{ firstName: "Bob", lastName: "Johnson", salary: 70000 },
{ firstName: "Alice", lastName: "Williams", salary: 85000 }
])
db.employees.countDocuments({})
db.employees.validate()
CRUD Operations
db.employees.find()
db.employees.find({ salary: { $gt: 75000 } })
db.employees.find(
{ department: "Engineering" },
{ firstName: 1, lastName: 1, salary: 1, _id: 0 }
)
db.employees.findOne({ email: "john@example.com" })
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $set: { salary: 90000 } }
)
db.employees.updateMany(
{ department: "Engineering" },
{ $set: { bonus: 5000 } }
)
db.employees.deleteOne({ _id: ObjectId("...") })
db.employees.deleteMany({ : })
Query Operators
db.employees.find({ salary: { $gt: 75000 } })
db.employees.find({ salary: { $gte: 75000 } })
db.employees.find({ salary: { $lt: 75000 } })
db.employees.find({ salary: { $lte: 75000 } })
db.employees.find({ salary: { $eq: 75000 } })
db.employees.find({ salary: { $ne: 75000 } })
db.employees.find({ skills: "JavaScript" })
db.employees.find({ skills: { $in: ["Python", "Go"] } })
db.employees.find({ skills: { : [, ] } })
db..({ : { : } })
db..({ : { : } })
db..({ : { : } })
db..({ : { : } })
Sorting and Limiting
db.employees.find().sort({ salary: -1 })
db.employees.find().sort({ salary: 1 })
db.employees.find().sort({ department: 1, salary: -1 })
db.employees.find().limit(10)
db.employees.find().skip(20).limit(10)
Indexing
db.employees.createIndex({ email: 1 })
db.employees.createIndex({ email: 1 }, { unique: true })
db.employees.createIndex({ department: 1, salary: -1 })
db.employees.createIndex({ firstName: "text", lastName: "text" })
db.employees.getIndexes()
db.employees.dropIndex("email_1")
db.employees.find({ $text: { $search: "john" } })
Data Types
{ name: "John Doe" }
{ age: 30, salary: 75000.50 }
{ active: true }
{ createdDate: new Date() }
{ skills: ["JavaScript", "Python"] }
{ address: { city: "NYC", state: "NY" } }
{ _id: ObjectId() }
{ phone: null }
{ email: /gmail/ }
Bulk Operations
let bulk = db.employees.initializeUnorderedBulkOp()
bulk.find({ department: "Engineering" }).update({ $set: { bonus: 5000 } })
bulk.find({ salary: { $lt: 50000 } }).update({ $inc: { salary: 2000 } })
bulk.insert({ firstName: "New", lastName: "Employee" })
bulk.find({ _id: ObjectId("...") }).removeOne()
bulk.execute()
Aggregation Pipeline (Data Processing)
db.employees.aggregate([
{ $match: { salary: { $gt: 75000 } } },
{ $group: {
_id: "$department",
avgSalary: { $avg: "$salary" },
count: { $sum: 1 }
}},
{ $sort: { avgSalary: -1 } },
{ $limit: 5 }
])
db.employees.aggregate([
{ $project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
salary: 1,
yearing_salary: { $multiply: ["$salary", 12] },
_id: 0
}}
])
db.employees.aggregate([
{ $unwind: "$skills" },
{ $group: {
_id: "$skills",
: { : }
}},
{ : { : - } }
])
db..([
{ : {
: ,
: ,
: ,
:
}},
{ : },
{ : {
: ,
: ,
: ,
:
}}
])
db..([
{ : { : { : () } } },
{ : {
: { : { : }, : { : } },
: { : },
: { : },
: { : }
}},
{ : { : , : } },
{ : {
: ,
: ,
: { : [, ] },
: { : [, ] },
: ,
:
}}
])
Transactions (ACID)
const session = db.getMongo().startSession()
session.startTransaction()
try {
db.accounts.updateOne(
{ _id: "account1" },
{ $inc: { balance: -100 } },
{ session: session }
)
db.accounts.updateOne(
{ _id: "account2" },
{ $inc: { balance: 100 } },
{ session: session }
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
} finally {
session.endSession()
}
Update Operators
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $set: { salary: 90000 } }
)
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $inc: { salary: 5000 } }
)
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $push: { skills: "Kubernetes" } }
)
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $addToSet: { skills: "Docker" } }
)
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $pull: { skills: "COBOL" } }
)
db.employees.updateOne(
{ _id: ObjectId("...") },
{ : { : } }
)
db..(
{ : () },
{
: { : () },
: { : },
: { : }
}
)
Array Queries
db.employees.find({ skills: "Python" })
db.employees.find({
skills: { $elemMatch: { $eq: "JavaScript" } }
})
db.orders.updateOne(
{ _id: ObjectId("..."), "items.sku": "SKU123" },
{ $set: { "items.$.quantity": 5 } }
)
db.orders.find({
items: { $elemMatch: {
sku: "SKU123",
quantity: { $gt: 3 }
}}
})
Real-World Examples
E-commerce Product Catalog
db.products.insertOne({
_id: ObjectId(),
sku: "PROD-001",
name: "Laptop",
price: 999.99,
stock: 50,
categories: ["Electronics", "Computers"],
specs: {
cpu: "Intel i7",
ram: "16GB",
storage: "512GB SSD"
},
reviews: [
{ userId: "user1", rating: 5, comment: "Great!" },
{ userId: "user2", rating: 4, comment: "Good value" }
],
lastUpdated: new Date()
})
session.startTransaction()
db.products.updateOne({ sku: "PROD-001" }, { $inc: { stock: -1 } }, { session })
db.orders.insertOne({ productId: ObjectId(), quantity: 1 }, { session })
session.commitTransaction()
User Profiles with Flexible Schema
db.users.insertOne({
_id: ObjectId(),
username: "john_doe",
email: "john@example.com",
profile: {
firstName: "John",
lastName: "Doe",
bio: "Software engineer",
socialLinks: {
github: "john-doe",
twitter: "@johndoe"
}
},
preferences: {
theme: "dark",
notifications: true,
language: "en"
},
metadata: {
createdAt: new Date(),
lastLogin: new Date(),
loginCount: 42
}
})
db.users.updateOne(
{ username: "john_doe" },
{ $set: { "profile.avatar": "url", "preferences.emailFrequency": "weekly" } }
)
Performance Tips
db.employees.createIndex({ email: 1 })
db.employees.createIndex({ department: 1, salary: -1 })
db.employees.find({ salary: { $gt: 75000 } }).explain("executionStats")
db.employees.find(
{ salary: { $gt: 75000 } },
{ firstName: 1, lastName: 1, salary: 1, _id: 0 }
)
db.employees.insertMany(largeArray, { ordered: false })
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $lookup: { from: "customers", ... } },
{ $group: { _id: "$customerId", total: { : } } }
])
Next Steps
Learn NoSQL design patterns, denormalization strategies, and advanced schema design in the nosql-design skill.