DEV Community

Mayank Singh
Mayank Singh

Posted on • Edited on • Originally published at msn2106.github.io

Revise All Basics of MongoDB in 10 Minutes 🚀

Want to revise MongoDB quickly before an interview or task? Here's your ultimate 10-minute refresher!

Mongo DB Architecture

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"
}
Enter fullscreen mode Exit fullscreen mode

🔤 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)

brew tap mongodb/brew
brew update
brew install mongodb-community@8.0
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

In a new terminal:

mongosh
Enter fullscreen mode Exit fullscreen mode

🧪 Essential MongoDB Shell Commands

🔎 Current Database

db
Enter fullscreen mode Exit fullscreen mode

📃 List All Databases

show databases
Enter fullscreen mode Exit fullscreen mode

➡️ Switch Database

use myDB
Enter fullscreen mode Exit fullscreen mode

If myDB doesn’t exist, it gets created when data is inserted.

❌ Drop Current Database

db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

📂 Collections and Documents

✅ Create a Collection

db.createCollection("testCollection")
Enter fullscreen mode Exit fullscreen mode

OR insert directly to auto-create:

db.testCollection.insertOne({ name: "Alice", age: 25 })
Enter fullscreen mode Exit fullscreen mode

📥 Insert Documents

// Single
db.testCollection.insertOne({ name: "Bob", age: 30 })

// Multiple
db.testCollection.insertMany([
  { name: "Carol", age: 22 },
  { name: "Dave", age: 29, city: "Delhi" }
])
Enter fullscreen mode Exit fullscreen mode

🔍 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
Enter fullscreen mode Exit fullscreen mode

More operators: $gt, $gte, $lte, $ne, $and, $or

db.testCollection.find({
  $and: [{ age: { $lt: 25 } }, { city: "Delhi" }]
})
Enter fullscreen mode Exit fullscreen mode

🔄 Update & Delete

✏️ Update

db.testCollection.update({ age: 22 }, { $set: { age: 24 } })

// Remove a field
db.testCollection.update({ name: "Carol" }, { $unset: { age: "" } })
Enter fullscreen mode Exit fullscreen mode

❌ Delete

db.testCollection.remove({ name: "Carol" }) // Delete specific
db.testCollection.remove({})                // Delete all
Enter fullscreen mode Exit fullscreen mode

🗑️ Drop Collection

db.testCollection.drop()
Enter fullscreen mode Exit fullscreen mode

📌 Sorting and Limiting

db.testCollection.find().limit(2)
db.testCollection.find().sort({ name: 1 }) // Ascending
Enter fullscreen mode Exit fullscreen mode

⚡ Indexing

Without indexes, MongoDB scans all documents—inefficient!

✅ Create Index

db.testCollection.createIndex({ name: 1 }) // Ascending
Enter fullscreen mode Exit fullscreen mode

❌ Drop Index

db.testCollection.dropIndex({ name: 1 })
Enter fullscreen mode Exit fullscreen mode

🔎 Get All Indexes

db.testCollection.getIndexes()
Enter fullscreen mode Exit fullscreen mode

🔥 Drop All Indexes

db.testCollection.dropIndexes()
Enter fullscreen mode Exit fullscreen mode

🧠 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 })
Enter fullscreen mode Exit fullscreen mode

You can monitor index usage via:

db.collection.getIndexes()
db.collection.explain("executionStats").find({ field: "value" })
Enter fullscreen mode Exit fullscreen mode

⚖️ 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 })
Enter fullscreen mode Exit fullscreen mode

🔁 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"
    }
  }
])
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
alexbevi profile image
Alex Bevilacqua • Edited

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)