Want to revise MongoDB quickly before an interview or task? Here's your ultimate 10-minute refresher!
MongoDB is a powerful, open-source, NoSQL document-oriented database, widely recognized for its scalability and flexibility. It’s written in C++ and uses BSON (a binary representation of JSON) for storing data.
In this article, we’ll explore all the essential MongoDB concepts, setup steps, and commands—perfect for a quick revision!
📚 Core Concepts
1. Database
A database in MongoDB is a physical container for collections. Each database gets its own files on the system. A single MongoDB server can have multiple databases.
2. Collection
Think of a collection as the equivalent of a table in relational databases. It's a group of MongoDB documents. Collections are schema-less, allowing documents within them to have different fields and structures.
3. Document
The fundamental unit of data in MongoDB—a document is a key-value pair structure, stored in BSON format. Example:
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
🔤 MongoDB Data Types
- String: Most common. UTF-8 valid.
- Integer: 32-bit or 64-bit.
- Boolean: true/false.
- Double: Floating point numbers.
- Arrays: Store lists.
- Object: Embedded documents.
- Date: Stored in UNIX time.
- ObjectID: Unique document identifier.
- Null, Binary, Code, Regex, Symbol, etc.
⚙️ Installing MongoDB (macOS via Homebrew)
- Link : https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/#install-mongodb-community-edition
- https://www.mongodb.com/docs/mongodb-shell/install/#install-mongosh
brew tap mongodb/brew
brew update
brew install mongodb-community@8.0
Key MongoDB executables:
- mongod: MongoDB server daemon.
- mongosh: MongoDB shell (CLI client).
- mongos: For sharded cluster queries.
Setting Up (Windows Example)
mkdir C:\data\db
mongod
In a new terminal:
mongosh
🧪 Essential MongoDB Shell Commands
🔎 Current Database
db
📃 List All Databases
show databases
➡️ Switch Database
use myDB
If myDB doesn’t exist, it gets created when data is inserted.
❌ Drop Current Database
db.dropDatabase()
📂 Collections and Documents
✅ Create a Collection
db.createCollection("testCollection")
OR insert directly to auto-create:
db.testCollection.insertOne({ name: "Alice", age: 25 })
📥 Insert Documents
// Single
db.testCollection.insertOne({ name: "Bob", age: 30 })
// Multiple
db.testCollection.insertMany([
{ name: "Carol", age: 22 },
{ name: "Dave", age: 29, city: "Delhi" }
])
🔍 Query Documents
db.testCollection.find() // All documents
db.testCollection.find().pretty() // Prettified
db.testCollection.find({ name: "Carol" }) // Filter
db.testCollection.find({ age: { $lt: 25 } }) // Less than
More operators: $gt, $gte, $lte, $ne, $and, $or
db.testCollection.find({
$and: [{ age: { $lt: 25 } }, { city: "Delhi" }]
})
🔄 Update & Delete
✏️ Update
db.testCollection.update({ age: 22 }, { $set: { age: 24 } })
// Remove a field
db.testCollection.update({ name: "Carol" }, { $unset: { age: "" } })
❌ Delete
db.testCollection.remove({ name: "Carol" }) // Delete specific
db.testCollection.remove({}) // Delete all
🗑️ Drop Collection
db.testCollection.drop()
📌 Sorting and Limiting
db.testCollection.find().limit(2)
db.testCollection.find().sort({ name: 1 }) // Ascending
⚡ Indexing
Without indexes, MongoDB scans all documents—inefficient!
✅ Create Index
db.testCollection.createIndex({ name: 1 }) // Ascending
❌ Drop Index
db.testCollection.dropIndex({ name: 1 })
🔎 Get All Indexes
db.testCollection.getIndexes()
🔥 Drop All Indexes
db.testCollection.dropIndexes()
🧠 MongoDB vs RDBMS
Feature | MongoDB (NoSQL) | RDBMS (SQL) |
---|---|---|
Data Model | Document-oriented (BSON) | Relational (tables & rows) |
Schema | Dynamic, schema-less | Fixed schema |
Scalability | Horizontally scalable via sharding | Mostly vertical scaling |
Joins | Limited support (via $lookup ) |
Native and complex join support |
Transactions | Multi-document ACID (since v4.0) | Full ACID-compliant |
Data Retrieval | JSON-like query language | SQL |
Performance | Faster for unstructured or semi-structured data | Better for structured data |
Use Case | Big data, real-time analytics, fast iteration | Banking, legacy systems, ERP |
Storage | BSON (Binary JSON) | Relational format (tables) |
Examples | MongoDB, Couchbase, Cassandra | MySQL, PostgreSQL, Oracle |
🏗️ How MongoDB Handles Millions of Incoming API Requests
MongoDB is designed for high concurrency and horizontal scalability. Here's how it deals with massive loads:
🚀 Efficient Indexing
MongoDB supports single field, compound, text, geospatial, and hashed indexes.
- It automatically uses indexes to quickly locate documents.
- You can create indexes on frequently queried fields to reduce read latency.
- Background indexing allows index creation without blocking operations.
db.collection.createIndex({ field: 1 })
You can monitor index usage via:
db.collection.getIndexes()
db.collection.explain("executionStats").find({ field: "value" })
⚖️ Sharding (Horizontal Scaling)
- Sharding divides large data sets across multiple machines.
- MongoDB uses a shard key to distribute documents.
- A query router (mongos) sends requests to appropriate shards.
- Each shard is a replica set ensuring redundancy and high availability.
Sharding helps:
- Balance read/write load
- Store more data than one server can handle
- Achieve linear horizontal scaling
sh.enableSharding("myDatabase")
sh.shardCollection("myDatabase.myCollection", { userId: 1 })
🔁 Joins via Aggregation Framework
MongoDB didn’t support joins traditionally but now allows joins using $lookup in the aggregation pipeline.
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userDetails"
}
}
])
While not as performant or flexible as SQL joins, this is effective for many use cases where data is somewhat normalized.
🧠 Connection Management
- MongoDB uses non-blocking I/O and asynchronous processing.
- Connection pooling is supported by most drivers.
- Caching and efficient memory management via WiredTiger engine.
✅ Why Use MongoDB?
- Schema-less and flexible structure
- High performance at scale
- Easier horizontal scaling
- Fast development lifecycle
- Ideal for modern applications using microservices
🔚 Conclusion
MongoDB’s flexibility and dynamic nature make it a great fit for modern, scalable applications. With the commands and concepts above, you’re now ready to dive into MongoDB or revise it whenever needed in just 10 minutes!
Have any MongoDB experience, tricks, or tips? Share in the comments! 👇
Author: Mayank Singh
Portfolio: https://msn2106.github.io/
LinkedIn: @msn2106
Top comments (1)
MongoDB 4.4 is EOL - you should probably update the article to recommend installing 8.0 as the tap supports it (see mongodb.com/docs/manual/tutorial/i...).
Recommending the "mongo" CLI is also dated (this was removed in 5.0). The MongoDB Shell (mongosh) is what should be used (mongodb.com/products/tools/shell)