Concept
Document-Oriented NoSQL
In relational databases, data is split into structured rows and tables, requiring foreign keys to join relationships.
MongoDB stores data as documents (BSON format, a binary representation of JSON) grouped inside collections. Documents can have varying structures, nested objects, and arrays:
{
"_id": "60c72b2f9b1d8b2bad000001",
"name": "Ada Lovelace",
"email": "ada@example.com",
"skills": ["math", "programming"],
"profile": {
"title": "First Programmer",
"verified": true
}
}Basic CRUD Operations
- Create: Insert documents into a collection.
db.users.insertOne({ name: "Grace Hopper", email: "grace@example.com" }); - Read: Query documents using query filters.
db.users.find({ "profile.verified": true }); - Update: Modify existing documents using update operators like
$set,$push, or$inc.
Common Mistakes
1. Forgetting to use update operators like $set
If you run db.users.updateOne({ id: 1 }, { status: "active" }), MongoDB replaces the entire document with { status: "active" } instead of only updating the status field. Always wrap modifications in $set or other operators:
db.users.updateOne({ id: 1 }, { $set: { status: "active" } });2. Treating MongoDB like a relational database
Creating excessive joins (via $lookup) in MongoDB is slow because NoSQL databases are optimized for denormalized, nested data structures. Embed documents unless data relations change frequently.
Best Practices
- De-normalize by default: Nest data (like user addresses) inside the parent document if the data is read together and does not grow infinitely.
- Always limit queries: Never run
db.collection.find()on large production tables without.limit(n)offsets. - Use index projection: Select only the fields you need using
.find({}, { name: 1, email: 1 })to reduce memory and transfer bandwidth.
