MongoDB — Basics
MongoDB — Basics
Section titled “MongoDB — Basics”What it is
Section titled “What it is”- Document database. Stores BSON (binary JSON).
- Flexible schema — no enforced structure unless you add validators.
- Horizontally scalable via sharding.
Document model
Section titled “Document model”- Database → Collections → Documents (BSON).
- Documents up to 16MB.
- Nested documents, arrays, ObjectId, Decimal128, ISODate, UUID.
db.users.insertOne({ name: 'A', email: 'a@b.com' })db.users.insertMany([{...},{...}])
db.users.find({ age: { $gte: 18 } })db.users.findOne({ _id: ObjectId('...') })
db.users.updateOne({ _id }, { $set: { name: 'B' }, $inc: { logins: 1 } })db.users.updateMany({ active: false }, { $set: { archived: true } })
db.users.deleteOne({ _id })db.users.deleteMany({ status: 'dead' })
db.users.replaceOne({ _id }, { ...full doc... })Operators
Section titled “Operators”- Comparison:
$eq,$ne,$gt,$gte,$lt,$lte,$in,$nin. - Logical:
$and,$or,$not,$nor. - Element:
$exists,$type. - Array:
$all,$elemMatch,$size. - Update:
$set,$unset,$inc,$push,$pull,$addToSet,$pop,$rename.
Indexes
Section titled “Indexes”- Default
_idindex. Add others. - Types:
- Single field:
db.users.createIndex({ email: 1 })(1 asc, -1 desc). - Compound:
{a: 1, b: -1}. Leftmost prefix matters. - Multikey — auto when indexed field is array.
- Text:
db.posts.createIndex({ body: 'text' })for full-text search (basic). - 2dsphere — geospatial.
- Hashed — for sharding.
- TTL — auto-expire docs:
createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }). - Unique, partial, sparse, wildcard.
- Single field:
- Use
.explain('executionStats')to verify index use.
Aggregation pipeline
Section titled “Aggregation pipeline”db.orders.aggregate([ { $match: { status: 'paid' } }, { $group: { _id: '$user', total: { $sum: '$amount' } } }, { $sort: { total: -1 } }, { $limit: 10 }])Stages: $match, $project, $group, $sort, $limit, $skip, $unwind, $lookup (join), $facet, $bucket, $addFields, $out, $merge.
Transactions
Section titled “Transactions”- Multi-document transactions on replica sets (4.0+) and sharded clusters (4.2+).
- Performance overhead — use sparingly. Prefer single-document atomic ops where possible.
Replica sets
Section titled “Replica sets”- Primary + secondaries + optional arbiter.
- Async replication via oplog.
- Automatic failover (election) on primary loss.
- Read preference:
primary,primaryPreferred,secondary,secondaryPreferred,nearest. - Write concern:
w: 1(primary),w: 'majority'(durable). - Read concern:
local,available,majority,snapshot.
Sharding
Section titled “Sharding”- Horizontal partitioning across shards (each is a replica set).
- Shard key determines distribution. Choose carefully: high cardinality, low frequency, monotonic NOT good (hotspot last shard).
- Hashed sharding for even distribution; ranged for query locality.
- Config servers store metadata. mongos routes queries.
- Driver: official MongoDB driver (Node, Python
pymongo/motor, Go, Java). - ODM: Mongoose (Node), MongoEngine (Python).
- CLI:
mongosh. GUI: Compass.