MongoDB Features
MongoDB started as a simple document store and has grown into a complete data platform. This tutorial tours its most important features, what each one does, and a short example of how it looks in practice, so you know which tools are available before diving into the details in later tutorials.
1. Document Data Model
Data is stored as documents: sets of field-value pairs that can contain arrays and nested documents. A document mirrors an object in your code, so there is no mapping layer between rows and objects.
db.products.insertOne({
name: "Noise-cancelling Headphones",
price: 7999,
specs: { batteryHours: 30, bluetooth: "5.3" },
colors: ["black", "silver"]
})
2. Flexible Schema with Optional Validation
Documents in one collection can differ: a laptop and a T-shirt can live in the same products collection with different attributes. When you need rules, schema validation enforces them with JSON Schema:
db.createCollection("customers", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["email", "name"],
properties: { email: { bsonType: "string", pattern: "^.+@.+$" } }
} }
})
3. Rich Query Language
The MongoDB Query API filters on any field, including nested fields and array elements, with operators for comparisons, logic, regular expressions, geospatial conditions and more.
db.products.find(
{ price: { $lte: 10000 }, colors: "black", "specs.batteryHours": { $gte: 20 } },
{ name: 1, price: 1, _id: 0 }
).sort({ price: 1 })
4. Aggregation Pipeline
The aggregation pipeline processes documents through stages such as $match, $group, $sort, $lookup (join) and $project. It handles reporting and data transformation inside the database.
db.orders.aggregate([
{ $match: { status: "SHIPPED" } },
{ $unwind: "$items" },
{ $group: { _id: "$items.category", revenue: { $sum: { $multiply: ["$items.qty", "$items.price"] } } } },
{ $sort: { revenue: -1 } }
])
5. Powerful Indexing
Indexes make queries fast. MongoDB supports single-field, compound, multikey (array), text, geospatial, hashed, wildcard, TTL, unique, partial and clustered indexes. See the Indexing tutorial for details.
db.orders.createIndex({ customerId: 1, createdAt: -1 })
6. Replication and High Availability
A replica set keeps identical copies of the data on several servers. If the primary fails, the remaining members elect a new primary within seconds, and drivers reconnect automatically. See the Replication tutorial.
7. Sharding for Horizontal Scale
Sharding splits a large collection across several replica sets (shards) using a shard key. A router process, mongos, sends each query to the right shards. You can add shards as data grows, and MongoDB 8.0 makes it easier to move collections between shards and to change a shard key with resharding.
sh.shardCollection("shop.orders", { customerId: "hashed" })
8. ACID Transactions
Every write to a single document is atomic. When a change must touch several documents or collections together, use a multi-document transaction:
const session = db.getMongo().startSession()
const accounts = session.getDatabase("bank").accounts
session.withTransaction(() => {
accounts.updateOne({ _id: "A" }, { $inc: { balance: -500 } })
accounts.updateOne({ _id: "B" }, { $inc: { balance: 500 } })
})
session.endSession()
9. Change Streams
Change streams let applications subscribe to inserts, updates and deletes in real time, without polling. They power notifications, cache invalidation, audit trails and syncing data to other systems.
const stream = db.orders.watch([{ $match: { operationType: "insert" } }])
while (stream.hasNext()) { printjson(stream.next().fullDocument) }
10. Time Series Collections
Time series collections store measurements over time in a compressed, bucketed format, which saves storage and speeds up time-range queries.
db.createCollection("sensorReadings", {
timeseries: { timeField: "ts", metaField: "sensor", granularity: "minutes" },
expireAfterSeconds: 60 * 60 * 24 * 90 // keep 90 days of data
})
11. Geospatial Queries
Store GeoJSON points, lines and polygons, index them with a 2dsphere index, and ask questions like "which stores are within 5 km of me?"
db.stores.createIndex({ location: "2dsphere" })
db.stores.find({ location: { $near: {
$geometry: { type: "Point", coordinates: [73.8567, 18.5204] }, // [longitude, latitude]
$maxDistance: 5000 // metres
} } })
12. Full-Text and Vector Search
- A text index provides basic keyword search on any deployment.
- Atlas Search adds relevance-ranked full-text search with fuzzy matching, autocomplete and facets, built on Apache Lucene.
- Atlas Vector Search finds documents by semantic similarity of embeddings, for AI features such as semantic search and retrieval-augmented generation.
13. Security
- Authentication with SCRAM passwords, x.509 certificates, and in Enterprise and Atlas also LDAP, Kerberos and OIDC.
- Role-based access control with built-in and custom roles.
- Encryption in transit (TLS) and at rest.
- Client-Side Field Level Encryption and Queryable Encryption, which encrypt sensitive fields in the application so the server only ever stores ciphertext. MongoDB 8.0 adds range queries on encrypted fields.
- Auditing of administrative and data operations (Enterprise and Atlas).
14. GridFS for Large Files
Documents are limited to 16 MB. GridFS splits larger files into chunks stored across two collections, so files and their metadata can live in the database. For most applications, object storage such as Amazon S3 plus a reference in a document is simpler.
15. Drivers, Tools and Atlas
- Official drivers for Java, Kotlin, Python, Node.js, C#, Go, Rust, PHP, Ruby, C/C++ and more, plus Spring Data MongoDB for Spring Boot.
- mongosh and Compass for working with data interactively.
- MongoDB Atlas for fully managed clusters with automated backups, scaling, monitoring and multi-cloud deployment.
16. Summary
| Need | MongoDB feature |
|---|---|
| Store objects naturally | Document model, BSON |
| Evolve the data model safely | Flexible schema + schema validation |
| Query and analyse | Query API, aggregation pipeline |
| Fast reads | Indexes |
| Stay online | Replica sets |
| Grow beyond one server | Sharding |
| Change several documents together | Multi-document ACID transactions |
| React to changes in real time | Change streams |
| Metrics and IoT data | Time series collections |
| Location features | GeoJSON and 2dsphere indexes |
| Search and AI | Text indexes, Atlas Search, Atlas Vector Search |
| Protect data | Authentication, RBAC, TLS, Queryable Encryption, auditing |