MongoDB Cheatsheet
Dense quick reference for mongosh, CRUD, aggregation, indexes, transactions, replica sets, sharding, backup, monitoring and the Go and Laravel drivers (MongoDB 8.x manual, mongo-go-driver v2, laravel-mongodb).
Connection
| Task | Command | Notes |
|---|---|---|
| Connect locally | mongosh | Default mongodb://127.0.0.1:27017 |
| Connect with URI | mongosh "mongodb://user:pass@host1:27017,host2:27017/app?replicaSet=rs0&authSource=admin" | Quote the URI; list several members for a replica set |
| Atlas / DNS seed list | mongosh "mongodb+srv://cluster0.example.mongodb.net/app" | +srv reads SRV and TXT records; TLS is on by default |
| Run a script | mongosh --quiet --eval "db.runCommand({ping:1})" | --file script.js for files |
| Switch / list DB | use app / show dbs / show collections | use creates the DB lazily on first write |
| Current DB | db.getName() | db is the current database object |
| Server version | db.version() | Also db.hello() for topology info |
| Help | db.collection.help() / db.help() | Use .explain() on any query helper |
| Go DSN | mongodb://user:pass@host:27017/?maxPoolSize=100&retryWrites=true&w=majority | Pass to mongo.Connect(options.Client().ApplyURI(uri)) |
| Laravel DSN | DB_URI=mongodb://user:pass@host:27017/?authSource=admin | config/database.php connection with driver => mongodb and database |
References: mongosh options, Connection string options, mongosh help.
CRUD
| Task | Command | Notes |
|---|---|---|
| Insert one | db.users.insertOne({name:"Ana", age:30}) | Returns insertedId; _id auto-generated ObjectId |
| Insert many | db.users.insertMany([{...},{...}], {ordered:false}) | ordered:false continues after a failed document |
| Find all | db.users.find() | Cursor; it in mongosh shows the next 20 |
| Find with filter | db.users.find({age:{$gte:18}}, {name:1, _id:0}) | Second argument is the projection |
| Find one | db.users.findOne({email:"a@b.c"}) | Returns a document or null |
| Sort / limit / skip | db.users.find().sort({age:-1}).skip(20).limit(10) | Large skip is slow; prefer range on an indexed key |
| Count | db.users.countDocuments({active:true}) | estimatedDocumentCount() uses metadata (fast, no filter) |
| Distinct | db.users.distinct("country", {active:true}) | Result must fit in the maximum BSON size (16 MiB); otherwise use $group |
| Update one | db.users.updateOne({_id:id}, {$set:{age:31}}) | Always use an update operator or pipeline |
| Update many | db.users.updateMany({active:false}, {$set:{archived:true}}) | Not atomic across documents |
| Upsert | db.users.updateOne({email:e}, {$set:{n:1}}, {upsert:true}) | Needs a unique index to be race-safe |
| Replace | db.users.replaceOne({_id:id}, {name:"New"}) | Replaces the whole document except _id |
| Find and modify | db.users.findOneAndUpdate({_id:id}, {$inc:{n:1}}, {returnDocument:"after"}) | Atomic read-modify-write on one document |
| Delete | db.users.deleteOne({_id:id}) / deleteMany({...}) | deleteMany({}) removes all but keeps indexes |
| Bulk write | db.users.bulkWrite([{insertOne:{document:{}}},{updateOne:{filter:{},update:{}}}]) | Mixed operations, one round trip |
| Drop | db.users.drop() / db.dropDatabase() | Irreversible |
| Rename | db.users.renameCollection("people") | In a sharded cluster the source and target are exclusively locked on every shard (5.0+) |
| Create with validation | db.createCollection("orders",{validator:{$jsonSchema:{bsonType:"object",required:["total"]}}}) | validationAction:"error" or "warn" |
References: Methods reference, BSON limits.
Query operators
| Group | Operators | Notes |
|---|---|---|
| Comparison | $eq $ne $gt $gte $lt $lte $in $nin | {age:{$in:[20,30]}} |
| Logical | $and $or $nor $not | Implicit AND between sibling fields |
| Element | $exists $type | {x:{$exists:true}}; $type:"string" |
| Evaluation | $regex $expr $jsonSchema $mod $text $where | $expr compares fields; avoid $where (JS, slow, unsafe) |
| Array | $all $elemMatch $size | $elemMatch requires all conditions on the same element |
| Array positions | "tags.0", "items.price" | Dot notation for nested paths and array elements |
| Bitwise | $bitsAllSet $bitsAnySet | Rare |
| Geospatial | $geoWithin $geoIntersects $near $nearSphere | $near needs a 2dsphere index |
| Projection | {a:1}, {a:0}, $slice, $elemMatch | Do not mix include and exclude except for _id |
| Cursor helpers | .hint({idx:1}) .collation({locale:"en",strength:2}) .maxTimeMS(500) | Always set maxTimeMS on user-facing queries |
References: Query predicates.
Update operators
| Operator | Example | Notes |
|---|---|---|
$set / $unset | {$set:{"a.b":1}, $unset:{old:""}} | Dot notation for nested fields |
$setOnInsert | {$setOnInsert:{createdAt:new Date()}} | Applies only when an upsert inserts |
$inc / $mul | {$inc:{stock:-1}} | Atomic counters |
$min / $max | {$max:{best:score}} | Update only if the new value is lower or higher |
$rename | {$rename:{a:"b"}} | Field rename |
$currentDate | {$currentDate:{ts:true}} | Server time |
$push | {$push:{tags:{$each:["a","b"], $slice:-10}}} | $slice caps array length; $sort, $position too |
$addToSet | {$addToSet:{tags:"x"}} | No duplicates |
$pull / $pullAll | {$pull:{tags:"x"}} | Remove matching elements |
$pop | {$pop:{tags:1}} | 1 last, -1 first |
Positional $ | updateOne({"items.id":5},{$set:{"items.$.qty":2}}) | First matched element |
Filtered $[id] | updateMany({}, {$set:{"items.$[i].qty":0}}, {arrayFilters:[{"i.qty":{$lt:0}}]}) | All elements matching the filter |
All $[] | {$inc:{"items.$[].qty":1}} | Every element |
| Pipeline update | updateOne({_id:id}, [{$set:{full:{$concat:["$a"," ","$b"]}}}]) | Array form allows aggregation expressions |
References: Update operators.
Aggregation stages
| Stage | Example | Notes |
|---|---|---|
$match | {$match:{status:"paid"}} | Put first so it can use an index |
$project / $addFields / $set | {$addFields:{total:{$multiply:["$q","$p"]}}} | $set is an alias of $addFields |
$unset | {$unset:["secret"]} | Remove fields |
$group | {$group:{_id:"$country", n:{$sum:1}, avg:{$avg:"$age"}}} | Accumulators: $sum $avg $min $max $first $last $push $addToSet $count |
$sort / $limit / $skip | {$sort:{n:-1}}, {$limit:10} | $sort + $limit coalesce into top-k |
$unwind | {$unwind:{path:"$items", preserveNullAndEmptyArrays:true}} | One output document per array element |
$lookup | {$lookup:{from:"users", localField:"uid", foreignField:"_id", as:"user"}} | Left outer join; index foreignField; pipeline form for complex joins |
$facet | {$facet:{a:[...], b:[...]}} | Several pipelines over one input; 16 MB result limit |
$bucket / $bucketAuto | {$bucketAuto:{groupBy:"$price", buckets:5}} | Histograms |
$count | {$count:"n"} | Single count document |
$sortByCount | {$sortByCount:"$tag"} | Group + count + sort |
$replaceRoot / $replaceWith | {$replaceWith:"$user"} | Promote an embedded document |
$merge / $out | {$merge:{into:"daily", on:"_id", whenMatched:"replace"}} | Materialized views; $out replaces the target |
$unionWith | {$unionWith:{coll:"archive"}} | Append another collection |
$setWindowFields | {$setWindowFields:{partitionBy:"$u", sortBy:{t:1}, output:{run:{$sum:"$v", window:{documents:["unbounded","current"]}}}}} | Window functions (running totals, rank) |
$graphLookup | {$graphLookup:{from:"emp", startWith:"$mgr", connectFromField:"mgr", connectToField:"_id", as:"chain"}} | Recursive traversal |
$sample | {$sample:{size:5}} | Random documents |
$geoNear | {$geoNear:{near:{type:"Point",coordinates:[x,y]}, distanceField:"d"}} | Must be the first stage |
$search / $vectorSearch | Atlas Search stages | Atlas and Search-enabled deployments only |
| Options | db.c.aggregate(p, {allowDiskUse:true, maxTimeMS:5000}) | Stages over 100 MB spill to disk by default since 6.0 (allowDiskUseByDefault); allowDiskUse:false forbids it |
References: Aggregation stages, Pipeline limits, Pipeline optimization.
Aggregation expression operators
| Group | Operators | Notes |
|---|---|---|
| Arithmetic | $add $subtract $multiply $divide $mod $round $trunc $abs $ceil $floor | $round:["$x",2] |
| Comparison | $eq $ne $gt $gte $lt $lte $cmp | Array form inside expressions |
| Conditional | $cond $ifNull $switch | {$cond:{if:{$gt:["$x",1]}, then:"a", else:"b"}} |
| String | $concat $substrCP $toLower $toUpper $trim $split $regexMatch $regexFind $replaceAll | $indexOfCP, $strLenCP count code points |
| Array | $map $filter $reduce $size $arrayElemAt $slice $in $concatArrays $zip $first $last $sortArray | $filter:{input:"$a", as:"x", cond:{$gt:["$$x",1]}} |
| Object | $mergeObjects $objectToArray $arrayToObject $getField $setField | Dynamic key handling |
| Date | $dateToString $dateFromString $dateAdd $dateDiff $dateTrunc $year $month $dayOfWeek | Specify timezone explicitly |
| Type | $toInt $toString $toObjectId $toDate $convert $type $isNumber | $convert has onError and onNull |
| Set | $setUnion $setIntersection $setDifference $setEquals | Arrays as sets |
| Accumulators | $sum $avg $min $max $stdDevPop $top $bottom $firstN $lastN $maxN $minN | $top and $bottom take sortBy and output |
| Variables | $$ROOT $$CURRENT $$NOW $$REMOVE $$PRUNE | $$ double dollar for variables |
References: Expression operators, Aggregation variables.
Indexes
| Task | Command | Notes |
|---|---|---|
| Single field | db.u.createIndex({email:1}, {unique:true}) | Unique index also rejects duplicates for upserts |
| Compound | db.o.createIndex({status:1, createdAt:-1}) | Prefix rule: usable for status and status + createdAt |
| ESR rule | Equality, then Sort, then Range | Put equality fields first, sort next, range last |
| Text | db.p.createIndex({title:"text", body:"text"}) then {$text:{$search:"go driver"}} | One text index per collection; sort with {score:{$meta:"textScore"}} |
| TTL | db.s.createIndex({createdAt:1}, {expireAfterSeconds:3600}) | Date field or array of dates; the background task runs every 60 s, so expired documents can linger |
| Partial | db.o.createIndex({uid:1}, {partialFilterExpression:{status:"open"}}) | Query must include the filter to use it |
| Sparse | {sparse:true} | Indexes only documents that have the field |
| Wildcard | db.e.createIndex({"attrs.$**":1}) | For arbitrary keys; not a replacement for compound indexes |
| Hashed | db.u.createIndex({uid:"hashed"}) | Equality only; used for hashed sharding |
| 2dsphere | db.pl.createIndex({loc:"2dsphere"}) | GeoJSON queries |
| Multikey | index on an array field | Automatic; at most one array field per compound index |
| Collation | createIndex({n:1},{collation:{locale:"en",strength:2}}) | Query must use the same collation |
| Hide / unhide | db.c.hideIndex("idx") / unhideIndex | Test the effect of dropping without dropping |
| List / drop | db.c.getIndexes() / dropIndex("idx") | db.c.totalIndexSize() |
| Usage stats | db.c.aggregate([{$indexStats:{}}]) | Find unused indexes |
| Covered query | projection only index fields and _id:0 | Project only indexed fields and exclude _id (_id:0) unless it is in the index |
References: Index properties, TTL indexes, Query optimization.
Explain
| Task | Command | Notes |
|---|---|---|
| Query plan | db.o.find({s:"x"}).explain("executionStats") | Modes: queryPlanner, executionStats, allPlansExecution |
| Aggregation plan | db.o.explain("executionStats").aggregate([...]) | Shows stage-level stats |
| Good sign | IXSCAN, totalDocsExamined close to nReturned | Check executionTimeMillis |
| Bad sign | COLLSCAN, SORT (in-memory), totalKeysExamined far above nReturned | In-memory sort limit 100 MB |
| Force index | .hint("idx_name") | For diagnosis, not routine use |
| Plan cache | db.c.getPlanCache().list() / .clear() | Plans recompute after index changes |
References: Explain results, Plan cache.
Transactions (session API)
| Task | Command | Notes |
|---|---|---|
| Start session | const s = db.getMongo().startSession() | Needs a replica set or sharded cluster |
| Callback API | s.withTransaction(() => { c1.insertOne({...},{session:s}); c2.updateOne({...},{...},{session:s}) }) | Retries on TransientTransactionError and UnknownTransactionCommitResult |
| Manual | s.startTransaction({readConcern:{level:"snapshot"}, writeConcern:{w:"majority"}}) then s.commitTransaction() / s.abortTransaction() | Always s.endSession() |
| Time limit | transactionLifetimeLimitSeconds (default 60) | Long transactions pin the oldest snapshot |
| Lock wait | maxTransactionLockRequestTimeoutMillis (default 5) | Fails fast with WriteConflict |
| Size | MongoDB writes as many oplog entries as needed; each entry stays within 16 MB, so the old 16 MB total limit no longer applies | Keep transactions small |
| DDL | Collections and indexes can be created inside a transaction except in cross-shard write transactions; indexes only on new empty collections | Use write concern majority for create or drop |
| Single-document | Always atomic without a transaction | Embed data to avoid transactions |
References: Transactions, Production considerations, Callback API.
Read concern, write concern, read preference
| Setting | Values | Notes |
|---|---|---|
Write concern w | 1, majority, number, tag set | The implicit default is w: majority; change it cluster-wide with setDefaultRWConcern |
j | true | Wait for the on-disk journal |
wtimeout | milliseconds | Returns an error but the write may still apply |
| Read concern | local, available, majority, linearizable, snapshot | majority returns data acknowledged by a majority |
linearizable | Single-document reads; set maxTimeMS | Reflects all majority-acknowledged writes completed before the read; blocks if a majority is unavailable |
| Causal consistency | startSession({causalConsistency:true}) | Read-your-writes across secondaries |
| Read preference | primary, primaryPreferred, secondary, secondaryPreferred, nearest | db.getMongo().setReadPref("secondaryPreferred") |
| Max staleness | maxStalenessSeconds | Skips lagging secondaries; the minimum value was not found on the pages checked: not verified |
| Tag sets | {dc:"east"} | Route reads to labelled members |
| Retryable writes | retryWrites=true | Default on in modern drivers; not for multi updates |
| Defaults | db.adminCommand({setDefaultRWConcern:1, defaultWriteConcern:{w:"majority"}}) | Cluster-wide default |
References: Read concern, Write concern, Read preference, Retryable writes.
Replica set admin
| Task | Command | Notes |
|---|---|---|
| Initiate | rs.initiate({_id:"rs0", members:[{_id:0, host:"a:27017"},{_id:1, host:"b:27017"},{_id:2, host:"c:27017"}]}) | Run once on one member |
| Status | rs.status() | stateStr, optimeDate, health, lastHeartbeatMessage |
| Config | rs.conf() / rs.reconfig(cfg) | rs.conf() returns the config document to edit and pass to rs.reconfig |
| Add / remove | rs.add("d:27017") / rs.remove("d:27017") | Add an arbiter with rs.addArb() (avoid arbiters with w:majority) |
| Step down | rs.stepDown(60) | Primary becomes secondary for 60 s; use before maintenance |
| Priority | cfg.members[1].priority = 2; rs.reconfig(cfg) | 0 means never primary |
| Hidden / delayed | {hidden:true, priority:0, secondaryDelaySecs:3600} | Reporting or recovery copies |
| Votes | {votes:0} | At most 7 voting members |
| Lag | rs.printSecondaryReplicationInfo() | Seconds behind primary |
| Oplog | rs.printReplicationInfo() | Oplog window length; resize with replSetResizeOplog |
| Sync source | rs.syncFrom("host:27017") | Temporary override |
| Elections | electionTimeoutMillis (default 10000) | Controls failover detection |
| Freeze | rs.freeze(120) | Prevent a member from becoming primary |
References: Replica set configuration, Limits, rs.stepDown.
Sharding admin
| Task | Command | Notes |
|---|---|---|
| Status | sh.status() | Shards, databases, chunks, balancer state |
| Add shard | sh.addShard("rs1/h1:27018,h2:27018") | Each shard is a replica set |
| Enable DB | sh.enableSharding("app") | Not required to shard a collection since 6.0; optional primary shard argument |
| Hashed key | sh.shardCollection("app.events", {uid:"hashed"}) | Even writes; scatter-gather for range queries |
| Ranged key | sh.shardCollection("app.orders", {tenant:1, _id:1}) | Targeted queries on the prefix |
| Refine key | db.adminCommand({refineCollectionShardKey:"app.orders", key:{tenant:1,_id:1,day:1}}) | Add suffix fields to fix jumbo chunks |
| Reshard | db.adminCommand({reshardCollection:"app.orders", key:{cust:1}}) | Online; forceRedistribution:true reshards on the same key (8.0+); needs spare disk and I/O (version of introduction not verified) |
| Balancer | sh.getBalancerState() / sh.startBalancer() / sh.stopBalancer() | Stop before cluster-wide backups |
| Balancer window | config.settings with activeWindow | Limit migration to quiet hours |
| Zones | sh.addShardToZone("s1","EU") / sh.updateZoneKeyRange(ns,min,max,"EU") | Data locality |
| Chunk size | config.settings {_id:"chunksize", value:128} | Global range size; default 128 MB, allowed 1 to 1024 MB |
| Data distribution | db.events.getShardDistribution() | Per-shard size and chunk counts |
| Shard key rules | High cardinality, low frequency, non-monotonic | Monotonic keys hot-spot one shard |
| Drain shard | db.adminCommand({removeShard:"rs1"}) | Deprecated since 8.3 in favour of startShardDraining, shardDrainingStatus, commitShardRemoval; on older versions re-run to see progress |
References: Balancer administration, Modify range size, removeShard, Reshard a collection.
Users and roles
| Task | Command | Notes |
|---|---|---|
| Create user | db.createUser({user:"app", pwd:passwordPrompt(), roles:[{role:"readWrite", db:"app"}]}) | Create in the DB used as authSource |
| Built-in roles | read, readWrite, dbAdmin, dbOwner, userAdmin, clusterAdmin, clusterMonitor, backup, restore, root | Least privilege per application |
| Custom role | db.createRole({role:"ro_orders", privileges:[{resource:{db:"app",collection:"orders"}, actions:["find"]}], roles:[]}) | Fine-grained actions |
| Grant | db.grantRolesToUser("app", ["read"]) / revokeRolesFromUser | |
| Change password | db.changeUserPassword("app", passwordPrompt()) | |
| Show users | db.getUsers() / show roles | |
| Enable auth | security.authorization: enabled in mongod.conf | Add a keyFile or x.509 for internal auth |
| TLS | net.tls.mode: requireTLS, certificateKeyFile, CAFile | |
| Auth mechanism | SCRAM-SHA-256, MONGODB-X509, PLAIN (LDAP), MONGODB-OIDC, MONGODB-AWS | Set authMechanism in the URI |
References: Built-in roles, Configuration options, db.createUser.
Backup and restore
| Task | Command | Notes |
|---|---|---|
| Dump all | mongodump --uri="mongodb://..." --out=/backup/2026-01-01 | Logical; slow on large data |
| Dump one collection | mongodump --db=app --collection=orders --gzip --archive=orders.gz | |
| Consistent dump | mongodump --oplog | Replica set point-in-time consistency |
| Restore | mongorestore --uri="mongodb://..." --gzip --archive=orders.gz | --drop replaces existing collections |
| Oplog replay | mongorestore --oplogReplay --oplogLimit=<ts> | Point-in-time up to a timestamp |
| Namespace map | --nsFrom="app.*" --nsTo="staging.*" | Restore into another DB |
| Export / import | mongoexport --db=app --collection=u --out=u.json / mongoimport --file=u.json | JSON or CSV, loses some BSON types |
| Filesystem snapshot | db.fsyncLock() ... db.fsyncUnlock() | Locks writes for a filesystem-level snapshot; always unlock afterwards |
| Managed | Atlas Cloud Backup, Ops Manager | Managed backup options; details not verified |
References: mongodump, mongorestore, db.fsyncLock.
Monitoring
| Task | Command | Notes |
|---|---|---|
| Server stats | db.serverStatus() | Sections: connections, opcounters, wiredTiger.cache, globalLock, network, repl, metrics |
| Connections | db.serverStatus().connections | current, available, totalCreated |
| Cache pressure | db.serverStatus().wiredTiger.cache | Compare bytes currently in the cache to maximum bytes configured; dirty bytes |
| Current ops | db.currentOp({active:true, secs_running:{$gt:5}}) | Long-running operations |
| Kill op | db.killOp(opid) | Use $currentOp aggregation for cluster-wide view |
| Profiler on | db.setProfilingLevel(1, {slowms:100}) | Level 0 off, 1 slow only, 2 all; writes system.profile |
| Read profile | db.system.profile.find().sort({ts:-1}).limit(5) | Fields millis, planSummary, docsExamined, keysExamined |
| Collection stats | db.orders.stats() | storageSize, totalIndexSize, avgObjSize |
| DB stats | db.stats(1024*1024) | Sizes in MB |
| Slow log | slowOpThresholdMs in mongod.conf, logs in JSON | operationProfiling.slowOpThresholdMs in mongod.conf, logs in JSON |
| Top | mongotop, mongostat --discover | Per-collection time, per-node rates |
| Validate | db.orders.validate({full:true}) | Checks data and index integrity |
| Compact | db.runCommand({compact:"orders"}) | Attempts to release unneeded disk space to the OS |
| Logs | db.adminCommand({getLog:"global"}) |
References: serverStatus, Profiler, mongostat.
Common errors
| Error | Code | Cause and fix |
|---|---|---|
| DuplicateKey (E11000) | 11000 | Unique index violated; handle in code or use upsert. err.keyPattern shows the index |
| WriteConflict | 112 | Two writers touched the same document in a transaction; retry (callback API retries for you) |
| TransientTransactionError | label | Retry the whole transaction |
| UnknownTransactionCommitResult | label | Retry commitTransaction only |
| MaxTimeMSExpired | 50 | maxTimeMS exceeded; add an index or raise the limit |
| ExceededTimeLimit | 262 | Server-side time limit exceeded; check maxTimeMS and load |
| NotWritablePrimary | 10107 | Writing to a secondary or during election; driver retries once |
| NetworkTimeout / server selection timeout | 89 / driver | No suitable server within serverSelectionTimeoutMS (default 30 s); check replica set name and DNS |
| Unauthorized | 13 | Missing role or wrong authSource |
| AuthenticationFailed | 18 | Wrong credentials or mechanism |
| BSONObjectTooLarge | 10334 | Document over 16 MiB; split or use GridFS |
| QueryExceededMemoryLimitNoDiskUseAllowed | 292 | Blocking stage over 100 MB with disk use disallowed; add an index or allow allowDiskUse |
| CursorNotFound | 43 | Idle cursor timed out (cursorTimeoutMillis, default 10 min) or was killed; batch faster |
| StaleConfig | 13388 | Router has an old chunk map; the driver retries |
| JumboChunk | n/a | Chunk cannot split on a low-cardinality shard key; refine the key |
| IndexBuildAborted | 276 | Index build was aborted; check logs and re-run createIndex |
| BSON key rules | n/a | Field names cannot start with $ or contain . in most cases |
References: Error codes (server source).
Go driver (mongo-go-driver v2)
package main
import (
"context"
"errors"
"log"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(options.Client().
ApplyURI("mongodb://localhost:27017/?replicaSet=rs0").
SetMaxPoolSize(100))
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
orders := client.Database("app").Collection("orders")
_, err = orders.InsertOne(ctx, bson.D{{Key: "sku", Value: "a1"}, {Key: "qty", Value: 2}})
if mongo.IsDuplicateKeyError(err) {
log.Println("duplicate")
}
var doc bson.M
err = orders.FindOne(ctx, bson.D{{Key: "sku", Value: "a1"}}).Decode(&doc)
if errors.Is(err, mongo.ErrNoDocuments) {
log.Println("not found")
}
sess, _ := client.StartSession()
defer sess.EndSession(ctx)
_, err = sess.WithTransaction(ctx, func(tc context.Context) (any, error) {
return orders.UpdateOne(tc,
bson.D{{Key: "sku", Value: "a1"}},
bson.D{{Key: "$inc", Value: bson.D{{Key: "qty", Value: -1}}}})
})
if err != nil {
log.Fatal(err)
}
}References: mongo-go-driver v2 mongo package, options package.
Laravel (laravel-mongodb)
// config/database.php
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('DB_URI', 'mongodb://127.0.0.1:27017'),
'database' => 'app',
],
// app/Models/Order.php
use MongoDB\Laravel\Eloquent\Model;
class Order extends Model
{
protected $connection = 'mongodb';
protected $table = 'orders';
protected $fillable = ['sku', 'qty'];
}
// usage
Order::create(['sku' => 'a1', 'qty' => 2]);
Order::where('qty', '>', 1)->orderBy('created_at', 'desc')->get();
DB::connection('mongodb')->transaction(function () { /* Eloquent calls */ });| Task | Command | Notes |
|---|---|---|
| Install | composer require mongodb/laravel-mongodb | Needs the PHP mongodb extension |
| Raw aggregation | DB::table('orders')->raw(fn ($c) => $c->aggregate([...])) | $c is the native collection |
| Index in migration | Schema::connection('mongodb')->table('orders', fn ($t) => $t->index('sku')) | Also unique, expire for TTL |
| Embedded docs | embedsMany, embedsOne relations | Stored inside the parent document |
| Mongo-only query | whereRaw(['qty' => ['$gte' => 2]]) | Native operators |
References: Laravel MongoDB, Schema builder, Transactions.
References
- MongoDB manual: https://www.mongodb.com/docs/manual/
- mongosh: https://www.mongodb.com/docs/mongodb-shell/
- Aggregation reference: https://www.mongodb.com/docs/manual/reference/mql/aggregation-stages/
- Indexes and ESR: https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/
- Read and write concern: https://www.mongodb.com/docs/manual/reference/read-concern/
- Sharding: https://www.mongodb.com/docs/manual/sharding/
- Go driver: https://www.mongodb.com/docs/drivers/go/current/
- laravel-mongodb: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/