Skip to content

MongoDB Common Commands Cheat Sheet

MongoDB is an open-source database system based on distributed file storage and is one of the most popular NoSQL databases today. This cheat sheet focuses on common operations in the mongosh CLI.

Connectivity

Command Description
mongosh Connect to MongoDB on local port
use <db_name> Switch or create database
db Show current database
show dbs List all databases
show collections List all collections in current DB
exit Exit Shell

Collection Operations (DDL)

Command Description
db.createCollection("users") Manually create a collection
db.users.drop() Delete specified collection
db.users.stats() View collection statistics
db.users.renameCollection("people") Change collection name

Document Operations (CRUD)

Insert

// Insert docs
db.users.insertOne({ name: "Alice", age: 25 });
db.users.insertMany([{ name: "Bob" }, { name: "Charlie" }]);

Read

// Query docs
db.users.find().pretty(); 
db.users.find({ age: { $gt: 20 } }).sort({ age: 1 }).limit(10); 
db.users.findOne({ name: "Alice" }); 

Update

// Update docs
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } });
db.users.updateMany({ age: { $lt: 18 } }, { $set: { status: "minor" } });

Delete

// Delete docs
db.users.deleteOne({ _id: ObjectId("...") });
db.users.deleteMany({ status: "inactive" });

Common Operators

Type Operator Description
Comparison $gt, $gte, $lt, $lte, $ne Greater than, Greater than or equal, Less than, Less than or equal, Not equal
Logic $and, $or, $not, $nor And, Or, Not, Not-And Not-Or
Field $set, $unset, $inc, $rename Set value, Remove field, Increment update, Rename field
Array $push, $pop, $pull, $addToSet Add, Pop, Remove matches, Add unique

Aggregation Pipeline

db.orders.aggregate([
  { $match: { status: "A" } },
  { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
]);

Index Management

Command Description
db.users.createIndex({ name: 1 }) Create ascending index
db.users.createIndex({ email: 1 }, { unique: true }) Create unique index
db.users.getIndexes() Show all indexes
db.users.dropIndex("name_1") Delete an index