MongoDB Introduction
MongoDB is the world's most popular document database. Instead of tables and rows, it stores data as flexible, JSON-like documents, which match the objects you already use in Java, JavaScript, Python and other languages.
This tutorial explains what MongoDB is, how it organizes data, what makes it different from a relational database, which editions exist, what is new in MongoDB 8.0, and how to run your first commands in a few minutes.
1. What Is MongoDB?
MongoDB is a source-available, general-purpose NoSQL database built around documents. Its key characteristics:
- Document model: each record is a document with fields, nested objects and arrays.
- Flexible schema: documents in one collection may have different fields, and you can add validation rules where you need them.
- Rich queries: filter on any field, including inside arrays and nested documents, and analyse data with the aggregation pipeline.
- High availability: replica sets keep copies of the data on several servers and fail over automatically.
- Horizontal scaling: sharding spreads very large collections across many servers.
- Transactions: single-document writes are atomic, and multi-document ACID transactions are available when needed.
The name comes from the word humongous, reflecting the original goal of handling very large amounts of data.
2. A Short History
| Year | Milestone |
|---|---|
| 2007 | The company 10gen starts building MongoDB as part of a cloud platform |
| 2009 | MongoDB is released as a standalone open-source database |
| 2013 | 10gen renames itself MongoDB, Inc. |
| 2015 | WiredTiger becomes the default storage engine (MongoDB 3.2) |
| 2016 | MongoDB Atlas, the fully managed cloud service, launches |
| 2018 | Multi-document ACID transactions arrive in MongoDB 4.0; the Community Server moves to the SSPL licence |
| 2021–2023 | Time series collections (5.0), Queryable Encryption (7.0) and many query improvements |
| 2024 | MongoDB 8.0 focuses on performance, scaling and security |
3. How MongoDB Organizes Data
MongoDB has a simple hierarchy:
- A deployment (a single server, a replica set or a sharded cluster) holds many databases.
- A database holds collections.
- A collection holds documents.
- A document holds fields with values.
| Relational term | MongoDB term |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Primary key | _id field (created automatically if you do not supply one) |
| Join | Embedded documents, or $lookup in an aggregation |
| Index | Index |
4. Documents and BSON
You write documents in a JSON-like syntax, but MongoDB stores them in BSON (Binary JSON). BSON is faster to scan than text JSON and supports more data types, such as dates, 64-bit integers, high-precision decimals and binary data.
{
_id: ObjectId("6710b3f2c9a1d24e8f0a1b2c"), // unique id, generated automatically
title: "Practical Java Streams",
authors: ["R. Mehta"], // array
price: NumberDecimal("499.00"), // exact decimal for money
stock: 40,
published: ISODate("2025-03-14T00:00:00Z"), // real date type
publisher: { name: "Techie Press", country: "IN" } // embedded document
}
A single document can be up to 16 MB. That is plenty for normal records; large files are stored with GridFS or, more commonly, in object storage with a reference in the document.
5. Editions and Ways to Run MongoDB
| Option | What it is | Good for |
|---|---|---|
| MongoDB Atlas | Fully managed cloud database on AWS, Azure and Google Cloud, with a free tier | Most new projects; no servers to manage |
| Community Server | Free, source-available server you run yourself | Development, learning, self-hosted production |
| Enterprise Advanced | Commercial self-managed edition with extra security, auditing and management tools | Large organizations running their own infrastructure |
Useful companion tools: mongosh (the command-line shell), MongoDB Compass (a free graphical client), the Database Tools (mongodump, mongoimport and others), and official drivers for Java, Python, Node.js, C#, Go and many more languages.
6. What Is New in MongoDB 8.0
- Performance: broad internal optimizations make many reads, updates and bulk writes faster than in MongoDB 7.0.
- Easier scaling: unsharded collections can be moved between shards, resharding is faster, and a config server can also act as a shard (a config shard) to save hardware in small clusters.
- Queryable Encryption with range queries: encrypted fields can now be searched with range conditions such as greater-than or less-than, while the server never sees the plaintext.
- Query settings: administrators can attach settings, such as which indexes a query shape may use, without changing application code.
- Multi-collection bulk writes: a single
bulkWritecommand can insert, update and delete across several collections.
7. Your First MongoDB Commands
The quickest way to try MongoDB locally is Docker. Alternatively, create a free cluster in MongoDB Atlas and copy its connection string.
# Start MongoDB 8.0 in a container
docker run -d --name mongo8 -p 27017:27017 mongo:8.0
# Connect with the MongoDB Shell (install mongosh separately, or use the one in the container)
mongosh "mongodb://localhost:27017"
# or: docker exec -it mongo8 mongosh
Now create a database, insert a document and query it:
use bookstore // switch to (and later create) the database
db.books.insertOne({ title: "Practical Java Streams", category: "Java", price: 499 })
db.books.find({ price: { $lt: 500 } }) // books cheaper than 500
show dbs // bookstore now appears in the list
There was no CREATE DATABASE or CREATE TABLE: the database and the books collection were created automatically by the first insert.
The same thing from Java
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.2.0</version> <!-- use the latest 5.x release -->
</dependency>
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
public class FirstMongoApp {
public static void main(String[] args) {
try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
MongoCollection<Document> books = client.getDatabase("bookstore").getCollection("books");
books.insertOne(new Document("title", "Designing Event Systems")
.append("category", "Kafka")
.append("price", 650));
for (Document book : books.find(Filters.lt("price", 700))) {
System.out.println(book.toJson());
}
}
}
}
8. Where MongoDB Is a Good Fit
- Product catalogues where items have different attributes.
- User profiles, preferences and content management.
- Mobile and web back ends that change their data model often.
- IoT and event data, using time series collections.
- Real-time features built on change streams, such as notifications and live dashboards.
- AI applications that combine operational data with vector search on Atlas.
MongoDB is a weaker fit when an application is dominated by complex reporting across many highly normalized entities; a relational database or a data warehouse may serve that better.
9. Summary
- MongoDB is a document database: data is stored as BSON documents in collections inside databases.
- It offers flexible schemas, rich queries, replication, sharding and ACID transactions.
- You can run it as MongoDB Atlas in the cloud, or self-managed as Community or Enterprise.
- MongoDB 8.0 improves performance, makes scaling easier and extends Queryable Encryption.
- Databases and collections are created automatically when you first store data in them.