MongoDB Cheatsheet

Quick reference guide for MongoDB database operations

Introduction to MongoDB

MongoDB is a NoSQL document database that provides high performance, high availability, and easy scalability.

Key Concepts
  • Document: Basic unit of data (like a JSON object)
  • Collection: Group of documents (like a table)
  • Database: Physical container for collections
  • BSON: Binary JSON - MongoDB's storage format
  • Schema-less: No fixed structure for documents
Basic Example
// Insert a document
db.users.insertOne({
  name: "John Doe",
  age: 30,
  email: "john@example.com",
  hobbies: ["reading", "hiking"]
});

Setting Up MongoDB Environment

Installation
  • MongoDB Community Server
  • MongoDB Atlas (Cloud)
  • MongoDB Compass (GUI)
  • MongoDB Shell (mongosh)
Online Tools
  • MongoDB Atlas Free Tier
  • MongoDB Playground
  • MongoDB University
IDEs & Tools
  • MongoDB Compass
  • Robo 3T
  • Studio 3T
  • VS Code Extensions

Database and Collection Operations

Database Creation
// Switch to or create a database
use my_database;

// Show current database
db;
Collection Operations
// Create a collection
db.createCollection("users");

// Show collections
show collections;

// Drop a collection
db.users.drop();
Common Data Types
  • String: UTF-8 text
  • Number: Integer/Double
  • Date: Timestamp
  • Array: List of values
  • ObjectId: Unique ID
  • Boolean: true/false

CRUD Operations

Create Operations
// Insert one document
db.users.insertOne({
  name: "Alice",
  age: 28,
  status: "active"
});

// Insert multiple documents
db.users.insertMany([
  {name: "Bob", age: 32},
  {name: "Charlie", age: 25}
]);
Read Operations
// Find all documents
db.users.find();

// Find with filter
db.users.find({age: {$gt: 25}});

// Find one document
db.users.findOne({name: "Alice"});
Update Operations
// Update one document
db.users.updateOne(
  {name: "Alice"},
  {$set: {status: "inactive"}}
);

// Update multiple documents
db.users.updateMany(
  {age: {$lt: 30}},
  {$inc: {age: 1}}
);
Delete Operations
// Delete one document
db.users.deleteOne({name: "Bob"});

// Delete multiple documents
db.users.deleteMany({status: "inactive"});

Querying Documents

Comparison Operators
// Greater than
db.products.find({price: {$gt: 100}});

// Less than or equal
db.products.find({price: {$lte: 50}});

// Not equal
db.products.find({category: {$ne: "Electronics"}});

// In array
db.products.find({category: {$in: ["Books", "Movies"]}});
Logical Operators
// AND (implicit)
db.users.find({
  age: {$gt: 25},
  status: "active"
});

// OR
db.users.find({
  $or: [
    {age: {$lt: 20}},
    {age: {$gt: 30}}
  ]
});

// NOT
db.users.find({
  age: {$not: {$lt: 30}}
});

Working with Arrays

Array Query Operators
// Match array element
db.users.find({hobbies: "hiking"});

// Match all elements
db.users.find({
  hobbies: {$all: ["reading", "hiking"]}
});

// Match array size
db.users.find({
  hobbies: {$size: 3}
});

// Element at position
db.users.find({
  "hobbies.0": "reading"
});
Array Update Operators
// Add to array
db.users.updateOne(
  {name: "Alice"},
  {$push: {hobbies: "swimming"}}
);

// Add multiple to array
db.users.updateOne(
  {name: "Alice"},
  {$push: {hobbies: {$each: ["swimming", "cycling"]}}}
);

// Remove from array
db.users.updateOne(
  {name: "Alice"},
  {$pull: {hobbies: "reading"}}
);

Aggregation Framework

Basic Aggregation
// Group by and count
db.orders.aggregate([
  {$group: {
    _id: "$status",
    count: {$sum: 1},
    total: {$sum: "$amount"}
  }}
]);

// Match and project
db.users.aggregate([
  {$match: {age: {$gt: 25}}},
  {$project: {name: 1, age: 1}}
]);
Advanced Aggregation
// Lookup (join)
db.orders.aggregate([
  {$lookup: {
    from: "customers",
    localField: "customer_id",
    foreignField: "_id",
    as: "customer"
  }}
]);

// Unwind and group
db.users.aggregate([
  {$unwind: "$hobbies"},
  {$group: {
    _id: "$hobbies",
    count: {$sum: 1}
  }}
]);

Indexes and Performance

Creating Indexes
// Single field index
db.users.createIndex({email: 1});

// Compound index
db.users.createIndex({last_name: 1, first_name: 1});

// Text index
db.articles.createIndex({content: "text"});

// Unique index
db.users.createIndex({username: 1}, {unique: true});
Index Management
// List indexes
db.users.getIndexes();

// Drop index
db.users.dropIndex("email_1");

// Explain query
db.users.find({email: "test@example.com"}).explain();
Index Best Practices
  • Index fields frequently used in queries
  • Use compound indexes for common query patterns
  • Consider index selectivity (high cardinality fields)
  • Monitor query performance with explain()

MongoDB with Drivers

Node.js Example
// Connect to MongoDB
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

// Insert document
async function insertUser() {
  try {
    await client.connect();
    const db = client.db("myDB");
    const result = await db.collection("users")
      .insertOne({name: "John", age: 30});
    console.log(result.insertedId);
  } finally {
    await client.close();
  }
}
Python Example
# Connect to MongoDB
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")

# Query documents
db = client.myDB
users = db.users.find({"age": {"$gt": 25}})
for user in users:
    print(user["name"])

More MongoDB Resources

MongoDB Basics

Learn fundamental MongoDB concepts

View Notes
MongoDB INTERVIEW Qs

Test your knowledge with interview questions

Interview Qs

Want to Practice MongoDB?

Try these concepts with real-world exercises

Start Practicing Now