Quick Reference MongoDB Cheatsheet
MongoDB on one page — mongosh inserts, finds, updates, deletes, indexes,
the aggregation pipeline, $lookup, and the document rules interviews ask about.
10 sections 10 tables 14 code snippets Open mongosh mongosh "mongodb://localhost:27017" Pick a database use shop
db.books.insertOne({ title: "Dune", pages: 412 })
db.books.find({ title: "Dune" }) This page is mongosh and the server. Mongoose is a separate Node library with its own models. One, then many db.books.insertOne({
title: "Dune",
pages: 412,
tags: ["sf", "classic"],
author: { name: "Frank Herbert" }
})
db.books.insertMany([
{ title: "Neuromancer", pages: 271 },
{ title: "Foundation", pages: 255 }
]) Filter, project, page db.books.find(
{ pages: { $gte: 300 }, tags: "sf" },
{ title: 1, pages: 1, _id: 0 }
).sort({ pages: -1 }).limit(10) One element of an array db.books.find({
reviews: {
$elemMatch: { stars: { $gte: 4 }, by: "Ada" }
}
}) Change two fields db.books.updateOne(
{ title: "Dune" },
{ $set: { pages: 416 }, $inc: { editions: 1 } }
) Insert when missing db.books.updateOne(
{ title: "Dune" },
{
$set: { pages: 416 },
$setOnInsert: { createdAt: new Date() }
},
{ upsert: true }
) matchedCount: 1 and modifiedCount: 0 means the document was already in that state. updateOne changes the first match. Pass sort when several documents match and the choice matters. $setOnInsert runs only when the upsert inserts. One row, or the short ones db.books.deleteOne({ title: "Dune" })
db.books.deleteMany({ pages: { $lt: 100 } }) A compound index db.books.createIndex({ title: 1, pages: -1 })
db.books.createIndex(
{ title: 1 },
{ unique: true }
)
db.books.find({ title: "Dune" }).explain("executionStats") Match, group, sort db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: {
_id: "$customerId",
total: { $sum: "$amount" },
orders: { $sum: 1 }
}},
{ $sort: { total: -1 } },
{ $limit: 10 }
]) A left join db.orders.aggregate([
{ $lookup: {
from: "books",
localField: "bookId",
foreignField: "_id",
as: "book"
}},
{ $unwind: {
path: "$book",
preserveNullAndEmptyArrays: true
}}
]) Embed the data you read together db.books.insertOne({
title: "Dune",
author: { name: "Frank Herbert" },
tags: ["sf", "classic"]
})
db.books.find({ "author.name": "Frank Herbert", tags: "sf" }) The update document db.books.updateOne(
{ title: "Dune" },
{ $set: { pages: 416 } }
) The id type db.books.findOne({
_id: ObjectId("6740aabbccddeeff00112233")
}) How to use this page: open mongosh, use shop, and insertOne a book. Then find it with a projection that drops _id, and updateOne the page count with $set. |