Most popular document database. Flexible schema.
Installation¶
docker run -d --name mongo -p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=secret \
mongo:7
CRUD¶
db.users.insertOne({name:'John',email:'[email protected]',age:30})
db.users.find({age:{$gt:25}})
db.users.updateOne({name:'John'},{$set:{age:31}})
db.users.deleteOne({name:'John'})
Schema¶
- Embed — 1:1, 1:few
- Reference — 1:many, many:many
- Denormalization OK
Indexes¶
db.users.createIndex({email:1},{unique:true})
db.orders.createIndex({userId:1,createdAt:-1})
Schema Design¶
When designing a MongoDB schema, choose between embedding and referencing based on data relationships. Embedding (nested documents) is ideal for data that is read together — for example, a user with their addresses. Use referencing (linking via ObjectId) for many-to-many relationships or documents that grow without bounds.
MongoDB supports schema validation using JSON Schema, which allows you to enforce data types and required fields even in a document database. For production deployment, always enable authentication, set up a replica set for high availability, and monitor performance using mongostat and mongotop. Atlas (managed MongoDB) offers automatic scaling, backups, and monitoring without the need for infrastructure management.
MongoDB for Flexible Data¶
Rapid prototyping, CMS, catalogs.