Learn MongoDB basics including CRUD operations, indexing, and aggregation using modern MongoDB 6.x features.
MongoDB is a NoSQL, document-oriented database that stores data as BSON (binary JSON). Collections hold documents, similar to how tables hold rows in SQL.
mongosh (MongoDB Shell) to run these commands interactively.# START the MongoDB service mongod --dbpath /data/db # Connect USING Mongo Shell mongosh # CHECK the CURRENT DATABASE > db
# Switch OR CREATE a NEW DATABASE > USE shop # SHOW ALL DATABASES > SHOW dbs
# INSERT a single document
> db.products.insertOne({ name: "Laptop", price: 1200, tags: ["electronics", "sale"] })
# INSERT multiple documents
> db.products.insertMany([
{ name: "Phone", price: 800, specs: { color: "black", memory: "128GB" } },
{ name: "Tablet", price: 600, specs: { color: "white", memory: "256GB" } }
])
# RETURN ALL documents
> db.products.find()
# Find WITH a filter
> db.products.find({ price: { $gt: 700 } })
# Project specific fields
> db.products.find({}, { name: 1, price: 1 })
# Find USING nested field
> db.products.find({ "specs.memory": "128GB" })
# UPDATE one document
> db.products.updateOne(
{ name: "Phone" },
{ $SET: { price: 850, "specs.color": "blue" } }
)
# UPDATE many
> db.products.updateMany({ price: { $lt: 1000 } }, { $inc: { price: 50 } })
# DELETE a document
> db.products.deleteOne({ name: "Tablet" })
# CREATE an INDEX ON price
> db.products.createIndex({ price: 1 })
# CREATE a compound INDEX
> db.products.createIndex({ name: 1, price: -1 })
# VIEW indexes
> db.products.getIndexes()
# Simple aggregation
> db.products.aggregate([
{ $match: { price: { $gt: 700 } } },
{ $GROUP: { _id: NULL, avgPrice: { $AVG: "$price" }, maxPrice: { $MAX: "$price" } } }
])
# Unwind arrays AND GROUP BY tag
> db.products.aggregate([
{ $unwind: "$tags" },
{ $GROUP: { _id: "$tags", COUNT: { $SUM: 1 } } }
])
For more examples, see MongoDB Aggregation Complete Examples.
MongoDB encourages embedding related data when it makes sense. However, referencing via ObjectId is possible too:
# Example of embedding
> db.orders.insertOne({
order_id: 1,
customer: { name: "Alice", email: "alice@example.com" },
items: [
{ product_id: ObjectId("..."), quantity: 2 },
{ product_id: ObjectId("..."), quantity: 1 }
]
})
$eq, $ne, $gt, $gte, $lt, $lte $IN, $nin $AND, $OR, $NOT $EXISTS, $type $SET, $unset, $inc, $push, $pull $regex, $TEXT, $search $lookup (FOR joins), $project, $GROUP, $sort, $LIMIT