A Beginner's Walkthrough to MongoDB: Key Concepts Simplified
In our previous REST API implementation, journal entries were stored in temporary, in-memory Java collections. As a result, restarting the Spring Boot application caused all journal entries to be completely lost. To solve this limitation, we transition to persistent storage using MongoDB—a popular document-oriented NoSQL database—ensuring our application data remains safe across server restarts.
1. The Persistence Problem: In-Memory Storage vs. Database Storage
When developing applications, relying solely on runtime memory (such as Java List or Map data structures) presents a major architectural bottleneck: volatility.
The Solution: Database Persistence
By integrating MongoDB into our Spring Boot application:
- Journal entries are serialized and written directly to disk storage.
- The state of the application persists independently of the application lifecycle.
- Multiple instances of the Spring Boot application can interact with the same centralized dataset.
2. Core Mental Model: Relational Databases (RDBMS) vs. MongoDB
To quickly grasp MongoDB, it helps to map its primary concepts to familiar Relational Database Management System (RDBMS) structures like MySQL.
Note: While MySQL enforces strict predefined schemas with rigid tables and rows, MongoDB is schema-less by default and stores data as flexible, JSON-like document structures (BSON).
Key Terminology Mapping
3. Structural Granularity: Databases, Collections, Fields, and Documents
To understand how data is organized inside MongoDB, let us break down a practical school database example:
1. Document
A single JSON-like data record. In MongoDB, a document representing a student looks like this:
{
"_id": "65cb12f8e12a3b4c5d6e7f8a",
"name": "Ram",
"age": 20
}
2. Collection
An ensemble of documents. In our example, the students collection holds individual student documents (Ram, Shyam, etc.).
3. Field
A key-value pair inside a document. Here, name and age serve as fields containing specific value types.
4. Launching the MongoDB Shell (mongosh) and Database Contexts
Before letting Spring Boot handle database operations programmatically, interactive command-line operations help build a concrete mental model of MongoDB.
Shell Launch Commands Across Operating Systems
Depending on your host operating system, starting the MongoDB CLI environment varies slightly:
- Windows Environment: Launch the shell directly using
mongosh:BASHmongosh - Linux / Fedora Environments: Start the background daemon service or use
mongod/mongosh:BASHsudo systemctl start mongod # or mongosh
Listing Databases and Context Switching
Once connected to the MongoDB shell instance, execute basic administrative commands:
// List all existing databases on the cluster
show dbs
To switch to a specific database context:
use school
Note on "On-The-Fly" Creation: If the
schooldatabase does not exist yet, MongoDB switches to it speculatively. The database is lazily created on disk only after your first data insertion.
5. Dynamic Collection Creation and Document Insertion (insertOne)
In traditional SQL databases, you must execute a explicit CREATE TABLE query defining column types before inserting data. MongoDB simplifies this process by implicitly creating collections on the fly during your first document insertion.
Inserting Documents into a Collection
To insert a document into a collection named students, invoke db.<collection_name>.insertOne(...):
// Inserting the first student document
db.students.insertOne({
"name": "Ram",
"age": 20
})
// Inserting a second student document
db.students.insertOne({
"name": "Shyam",
"age": 200
})
Verifying Collection Creation
Now check the active collections in the school database:
show collections
// Output: students
6. Data Retrieval (find, .pretty()) and Auto-Generated Primary Keys
To query existing data stored inside a collection, use find().
Reading All Documents
db.students.find()
To format dense output into readable indented JSON formatting, append .pretty():
db.students.find().pretty()
Output Structure:
[
{
"_id": ObjectId("65cb911a3d12f45a0b81c101"),
"name": "Ram",
"age": 20
},
{
"_id": ObjectId("65cb912b3d12f45a0b81c102"),
"name": "Shyam",
"age": 200
}
]
Deep Dive: The Auto-Generated _id Field
Notice that we did not supply an _id field in our insertOne command.
- Automatic Generation: MongoDB automatically assigns a globally unique primary key named
_idto every new document. - Type: By default,
_iduses the 12-byteObjectIdstructure encoding timestamp, machine hash, process ID, and a incrementing counter. - Uniqueness: Guarantees that every document across your collection can be uniquely targeted and updated.
Querying Documents with Filters
To search for specific records, pass a filter criteria JSON object into find():
// Query for documents where name matches "Ram"
db.students.find({ "name": "Ram" })
7. Document Deletion Strategies (deleteOne, deleteMany)
MongoDB provides straightforward functions to remove documents using matching filter objects.
Single Document Deletion
To delete the first document matching a condition, use deleteOne():
// Delete a single document matching the name "Ram"
db.students.deleteOne({ "name": "Ram" })
Bulk Document Deletion
To delete all documents that match a condition:
db.students.deleteMany({ "age": { $gte: 20 } })
Verifying Deletion Execution
Checking the remaining records in the collection after deleting "Ram":
db.students.find()
Output:
[
{
"_id": ObjectId("65cb912b3d12f45a0b81c102"),
"name": "Shyam",
"age": 200
}
]
8. Command Cheat Sheet & Operations Summary
Here is a practical reference table summarizing key MongoDB shell commands:
9. How Spring Boot Integrates with MongoDB
While knowing the basic CLI commands is useful, in real-world Java development, we rarely interact with the raw mongosh shell directly.
Instead, Spring Boot leverages Spring Data MongoDB to abstract away shell interactions:
Key Differences in Spring Boot:
- Java POJO Mapping: Java classes marked with
@Documentcorrespond to MongoDB collections. - Fields & Identifiers: Class fields marked with
@Idmap directly to MongoDB's internal_idkey. - Repository Automation: Spring Boot interfaces extending
MongoRepositoryautomatically handle basic CRUD operations without writing raw CLI queries.
Summary and Key Takeaways
- Persistence Necessity: In-memory storage causes total data loss during application restarts. External databases like MongoDB solve this issue by keeping data persistent on disk.
- Relational vs. Document Paradigm: SQL Tables map to MongoDB Collections, SQL Rows map to Documents, and SQL Columns map to Fields.
- Flexible JSON/BSON Data: MongoDB stores documents as flexible key-value structures without enforcing rigid database table schemas upfront.
- Implicit Creation: Both databases and collections are created lazily on the fly when you first insert data into them.
- Automatic
_idPrimary Key: MongoDB automatically attaches a unique_id(ObjectId) key to every document to guarantee record uniqueness. - Basic CLI Flow: Use
use <db>to select context,insertOne()to save data,find()to query records, anddeleteOne()to clear entries. - Spring Boot Abstraction: Direct CLI usage is primarily for learning and debugging; production applications use Spring Data MongoDB to manage queries automatically via Java annotations.