DEV Community

Cover image for A Complete Guide to MongoDB for Developers (With Code Examples)
Farhad Rahimi Klie
Farhad Rahimi Klie

Posted on

A Complete Guide to MongoDB for Developers (With Code Examples)

MongoDB has become one of the most popular NoSQL databases in the world. Its flexible schema, JSON-like documents, and developer-friendly ecosystem make it a top choice for modern applications, from small side projects to large-scale enterprise systems.

In this article, you will learn everything you need to know to get started with MongoDB, from installation to CRUD operations, indexes, aggregation, schema design, and best practices.

1. What Is MongoDB?

MongoDB is a NoSQL document database that stores data in BSON (Binary JSON) format. Unlike relational databases, MongoDB does not require predefined schemas, making it more flexible for fast-moving projects and distributed systems.

Key MongoDB Features

  • Schema-less documents
  • Horizontal scaling + sharding
  • High availability with replica sets
  • Rich query language
  • Aggregation framework
  • Integrated indexing
  • Great performance for read/write-heavy applications

2. MongoDB Architecture Overview

MongoDB stores data using the following hierarchy:

MongoDB
 └── Database
      └── Collection
            └── Document
                  └── Field (key/value)
Enter fullscreen mode Exit fullscreen mode

Example:

myDatabase
 └── users (collection)
        └── { name: "Klie", age: 22 } (document)
Enter fullscreen mode Exit fullscreen mode

3. Installing & Connecting to MongoDB

Install MongoDB on your system

You can install MongoDB Community Edition using:

  • Windows: MSI Installer
  • macOS: brew install mongodb-community
  • Linux: Official MongoDB repository

Connect using the Mongo Shell

mongosh
Enter fullscreen mode Exit fullscreen mode

Connect in Node.js (using Mongoose)

import mongoose from "mongoose";

mongoose.connect("mongodb://localhost:27017/mydb")
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

4. Basic MongoDB Commands

Show all Databases

show dbs
Enter fullscreen mode Exit fullscreen mode

Create/Use Database

use myDatabase
Enter fullscreen mode Exit fullscreen mode

Show Collections

show collections
Enter fullscreen mode Exit fullscreen mode

5. Creating a Collection & Inserting Documents

Insert One Document

db.users.insertOne({
  name: "Klie",
  age: 24,
  skills: ["C++", "Node.js", "MongoDB"]
});
Enter fullscreen mode Exit fullscreen mode

Insert Many Documents

db.users.insertMany([
  { name: "Farhad", age: 22 },
  { name: "Rahimi", age: 30 }
]);
Enter fullscreen mode Exit fullscreen mode

6. Querying Documents

Find All

db.users.find();
Enter fullscreen mode Exit fullscreen mode

Find with Conditions

db.users.find({ age: { $gt: 20 } });
Enter fullscreen mode Exit fullscreen mode

Find One

db.users.findOne({ name: "Klie" });
Enter fullscreen mode Exit fullscreen mode

7. Updating Documents

Update One

db.users.updateOne(
  { name: "Klie" },
  { $set: { age: 25 } }
);
Enter fullscreen mode Exit fullscreen mode

Update Many

db.users.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "active" } }
);
Enter fullscreen mode Exit fullscreen mode

8. Deleting Documents

Delete One

db.users.deleteOne({ name: "Farhad" });
Enter fullscreen mode Exit fullscreen mode

Delete Many

db.users.deleteMany({ age: { $gt: 40 } });
Enter fullscreen mode Exit fullscreen mode

9. Indexing in MongoDB

Indexes help improve query performance.

Create Index

db.users.createIndex({ name: 1 });  // 1 = ascending
Enter fullscreen mode Exit fullscreen mode

List Indexes

db.users.getIndexes();
Enter fullscreen mode Exit fullscreen mode

Drop Index

db.users.dropIndex("name_1");
Enter fullscreen mode Exit fullscreen mode

10. The Aggregation Framework

Aggregation is like SQL’s GROUP BY.

Example: Group by age and count users

db.users.aggregate([
  { $group: { _id: "$age", total: { $sum: 1 } } }
]);
Enter fullscreen mode Exit fullscreen mode

Example: Sort by age

db.users.aggregate([
  { $sort: { age: 1 } }
]);
Enter fullscreen mode Exit fullscreen mode

Example: Match + Sort + Limit

db.users.aggregate([
  { $match: { age: { $gt: 20 } } },
  { $sort: { age: -1 } },
  { $limit: 5 }
]);
Enter fullscreen mode Exit fullscreen mode

11. Mongoose (Node.js ODM) Example

User Model

import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  skills: [String]
});

const User = mongoose.model("User", userSchema);

export default User;
Enter fullscreen mode Exit fullscreen mode

Create a User

const user = await User.create({
  name: "Klie",
  age: 24,
  skills: ["C++", "Node.js"]
});
Enter fullscreen mode Exit fullscreen mode

Find Users

const users = await User.find({ age: { $gt: 20 } });
Enter fullscreen mode Exit fullscreen mode

12. Schema Design Best Practices

Document-Oriented Mindset

Think in objects, not tables.

Embed when:

  • Data reads together
  • Many-to-one or one-to-few
  • Example: user + address

Reference when:

  • One-to-many with large counts
  • Example: user → 1,000 posts

Avoid deeply nested documents

Keep document size < 16MB.

13. Security Best Practices

  • Always use authentication (mongod --auth)
  • Use environment variables for connection strings
  • Enable role-based access control
  • Use TLS/SSL for production
  • Restrict access with IP whitelisting

14. MongoDB Use Cases

MongoDB is used in:

  • Real-time dashboards
  • E-commerce catalogs
  • Social media apps
  • Mobile backends
  • IoT applications
  • Logging systems
  • Content management platforms

15. Conclusion

MongoDB is a powerful, flexible, and highly scalable NoSQL database that fits modern development workflows very well. Whether you are building an e-commerce platform, a social media system, or a personal project, MongoDB offers simplicity and strong performance.

If you are working with JavaScript, Node.js, or full-stack applications, MongoDB integrates seamlessly and accelerates development time.

Top comments (0)