MongoDB stores data as flexible JSON-like documents instead of rows in rigid tables — a shift that changes how you model data, not just the syntax you type.
{
"_id": "64f...",
"name": "Amara",
"email": "amara@example.com",
"tags": ["admin", "beta-tester"]
}
A document is one record, stored as BSON (a binary form of JSON). A collection is a group of documents — roughly analogous to a table, except documents in the same collection don't need identical fields.
db.users.insertOne({ name: "Kofi", email: "kofi@example.com" })
db.users.find({ name: "Kofi" })
db.users.updateOne(
{ name: "Kofi" },
{ $set: { email: "new-kofi@example.com" } }
)
db.users.deleteOne({ name: "Kofi" })
find takes a query document — the fields to match — rather than a SQL-style WHERE clause. $set is an update operator that changes only the specified fields, leaving the rest of the document untouched.
db.users.find({ tags: "admin" }) // any user with "admin" in their tags array
db.users.find({ "address.city": "Nairobi" }) // dot notation reaches into nested documents
This is where MongoDB's document model pays off most visibly — related data that would need a JOIN in a relational database can live embedded in one document, if it's read together as often as it's written.
db.users.createIndex({ email: 1 })
Without an index, a query scans every document in the collection. An index on frequently-queried fields (email, a lookup key) turns that into a fast lookup — the same tradeoff as in any relational database.
Comments