Skip to content

MongoDB Cheatsheet — Query Quick Reference

DodaTech 3 min read

In this tutorial, you'll learn about MongoDB Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

MongoDB CRUD operations, query operators, aggregation pipeline, indexes, and database commands — a dense reference for daily NoSQL database work.

Database & Collection Commands

use mydb                    // switch/create database
db                          // current db
show dbs                    // list databases
show collections            // list collections
db.createCollection("users")
db.users.drop()
db.dropDatabase()

CRUD — Create

db.users.insertOne({ name: "Alice", age: 30, city: "NYC" });
db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
]);

CRUD — Read

db.users.find()                         // all documents
db.users.find({ age: { $gt: 25 } })    // filtered
db.users.findOne({ name: "Alice" })     // first match
db.users.find({}, { name: 1, _id: 0 }) // projection (only name)

Query Operators

Operator What it does
$eq, $ne Equal, not equal
$gt, $gte Greater than (or equal)
$lt, $lte Less than (or equal)
$in, $nin In array, not in array
$regex Pattern match
$exists Field exists
$and, $or Logical AND/OR
db.users.find({ age: { $gte: 18, $lte: 65 } });
db.users.find({ name: { $regex: "^A", $options: "i" } });
db.users.find({ $or: [{ city: "NYC" }, { age: { $lt: 20 } }] });
db.users.find({ "address.zip": "10001" });  // nested field

CRUD — Update

db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31 } }
);
db.users.updateMany(
  { city: "NYC" },
  { $inc: { visits: 1 } }
);
db.users.replaceOne(
  { name: "Bob" },
  { name: "Bob", age: 26, city: "LA" }
);

Update operators: $set, $unset, $inc, $push, $pull, $addToSet, $rename.

CRUD — Delete

db.users.deleteOne({ name: "Charlie" });
db.users.deleteMany({ age: { $lt: 18 } });
db.users.deleteMany({});                     // all documents

Aggregation Pipeline

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$customer_id", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 },
  { $project: { customer_id: 1, total: 1, _id: 0 } }
]);
Stage Purpose
$match Filter documents
$group Group by field, compute aggregations
$sort Sort documents
$project Reshape fields
$limit Limit results
$lookup Left outer join with another collection
$unwind Deconstruct array
$count Count documents

Aggregation operators: $sum, $avg, $min, $max, $first, $last, $push, $addToSet.

Indexes

db.users.createIndex({ email: 1 });              // ascending
db.users.createIndex({ city: 1, age: -1 });     // compound
db.users.createIndex({ name: "text" });          // text index
db.users.createIndex({ created_at: 1 }, { expireAfterSeconds: 86400 });  // TTL
db.users.getIndexes();
db.users.dropIndex("email_1");

Useful Methods

db.users.countDocuments({ age: { $gt: 30 } });
db.users.distinct("city");
db.users.find().sort({ age: -1 }).skip(10).limit(5);
db.users.find().explain("executionStats");      // query performance
What is the difference between SQL and MongoDB?

MongoDB is a NoSQL document database — data is stored as JSON-like documents (BSON) with a flexible schema. Unlike SQL tables with fixed columns, each document in a MongoDB collection can have different fields. MongoDB trades strict consistency and joins (handled via $lookup) for scalability and developer flexibility.

What is the MongoDB aggregation pipeline?

The aggregation pipeline processes documents through a sequence of stages. Each stage transforms the data and passes it to the next stage. Common stages include $match (filter), $group (aggregate), $sort (order), and $lookup (join with another collection). It's MongoDB's equivalent of SQL's GROUP BY and JOIN operations.

How do indexes work in MongoDB?

Indexes store a sorted reference to a field, allowing MongoDB to find documents without scanning the entire collection. A single-field index on email speeds up queries filtering by email. A compound index on {city: 1, age: -1} supports queries filtering by city, then sorting or filtering by age. Indexes consume write overhead and disk space

See the full MongoDB tutorials for advanced pipelines.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro