Skip to main content
Databases

MongoDB & Mongosh Queries

Production

Document database operations, aggregation pipelines, update operators, compound indexes, and sharding fundamentals.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

MongoDB & Mongosh Queries Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (16 Total Commands).

16+ Verified Recipes
Connectingmongosh
mongosh "mongodb+srv://cluster.mongodb.net/app_db" --username admin

Open interactive mongosh terminal to Atlas cluster with authentication.

Document Queryingfind, $gte, sort, limit
db.users.find({ status: "active", age: { $gte: 21 } }, { name: 1, email: 1 }).sort({ createdAt: -1 }).limit(20)

Query documents matching conditions with field projection, sorting, and pagination limit.

Atomic UpdatesupdateOne, $set, $inc
db.users.updateOne({ _id: ObjectId("60d5ec...") }, { $set: { verified: true }, $inc: { loginCount: 1 } })

Atomically update specific document fields and increment counter without full rewrite.

Aggregation Pipelinesaggregate, $match, $group
db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } }, { $sort: { totalSpent: -1 } } ])

Filter, group, and compute totals using multi-stage aggregation pipeline.

Compound IndexescreateIndex, { unique: true }
db.users.createIndex({ companyId: 1, email: 1 }, { unique: true })

Create compound unique index to accelerate multi-field queries and prevent duplicates.

Query Analysisexplain("executionStats")
db.users.find({ email: "test@domain.com" }).explain("executionStats")

Inspect query execution plan, keys examined, and document scan statistics.

Bulk WritesbulkWrite
db.products.bulkWrite([ { insertOne: { document: { sku: "A1", price: 10 } } }, { updateOne: { filter: { sku: "A2" }, update: { $set: { price: 20 } } } } ])

Execute batch of write operations in a single network round-trip.

Relational Joins$lookup, $unwind
db.orders.aggregate([ { $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'customer' } }, { $unwind: '$customer' } ])

Perform left outer join across collections and deconstruct joined array to flat document structure.

TTL IndexesexpireAfterSeconds
db.sessions.createIndex({ 'createdAt': 1 }, { expireAfterSeconds: 86400 })

Create Time-To-Live index automatically deleting documents 24 hours after timestamp.

Text Search$text, $search
db.posts.createIndex({ content: 'text', title: 'text' }); db.posts.find({ $text: { $search: 'database scaling' } })

Build compound full-text index and execute relevance-scored search query.

Array Updates$push, $each, $slice
db.users.updateOne({ _id: ObjectId('...') }, { $push: { tags: { $each: ['dev', 'lead'], $slice: -5 } } })

Atomically append multiple values to an array while keeping only the last 5 elements.

Geospatial Indexing2dsphere, $near
db.places.createIndex({ location: '2dsphere' }); db.places.find({ location: { $near: { $geometry: { type: 'Point', coordinates: [-73.9667, 40.78] }, $maxDistance: 5000 } } })

Index geospatial coordinates and query points within 5,000 meters of longitude/latitude coordinates.

TransactionsstartSession, startTransaction
session = db.getMongo().startSession(); session.startTransaction(); try { session.getDatabase('store').orders.insertOne({ id: 1 }, { session }); session.commitTransaction(); } catch (e) { session.abortTransaction(); }

Execute multi-document ACID transaction across replica set collections.

Query ProfilingcurrentOp
db.currentOp({ 'active': true, 'secs_running': { '$gt': 5 } })

List currently executing database operations running longer than 5 seconds to diagnose bottlenecks.

Replica ClusterreplSetGetStatus
db.adminCommand({ replSetGetStatus: 1 })

Inspect replica set cluster topology, replication lag, and member health states.

Change Streamswatch
db.collection.watch([{ $match: { 'operationType': 'insert' } }])

Subscribe to real-time oplog event change stream for reactive microservice triggering.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

MongoDB & Mongosh Queries: Command Groups & Quick Index

16 indexed entries across 16 sections
Connecting1 items
Document Querying1 items
Atomic Updates1 items
Aggregation Pipelines1 items
Compound Indexes1 items
Query Analysis1 items
Bulk Writes1 items
Relational Joins1 items
TTL Indexes1 items
Text Search1 items
Array Updates1 items
Geospatial Indexing1 items
Transactions1 items
Query Profiling1 items
Replica Cluster1 items
Change Streams1 items

Highlighted Flags & Syntax Examples in MongoDB & Mongosh Queries

mongosh "mongodb+srv://cluster.mongodb.net/app_db" --username admin

Open interactive mongosh terminal to Atlas cluster with authentication.

Flags: mongosh
db.users.find({ status: "active", age: { $gte: 21 } }, { name: 1, email: 1 }).sort({ createdAt: -1 }).limit(20)

Query documents matching conditions with field projection, sorting, and pagination limit.

Flags: find, $gte, sort, limit
db.users.updateOne({ _id: ObjectId("60d5ec...") }, { $set: { verified: true }, $inc: { loginCount: 1 } })

Atomically update specific document fields and increment counter without full rewrite.

Flags: updateOne, $set, $inc
db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } }, { $sort: { totalSpent: -1 } } ])

Filter, group, and compute totals using multi-stage aggregation pipeline.

Flags: aggregate, $match, $group

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for MongoDB & Mongosh Queries.

What is the ESR rule for MongoDB compound index design?

ESR stands for Equality, Sort, Range. Place fields tested with exact equality first in the index, followed by fields used for sorting, and finally fields queried with range operators ($gte, $lt, $in) for optimal index traversal.

When should you use embedding vs referencing in MongoDB schemas?

Embed child documents when you have 1-to-few relationships and child data is always queried together with the parent. Use references (foreign IDs) when child data grows unboundedly (1-to-many), is queried independently, or requires large document updates.

What is the difference between Write Concern (w: majority) and Read Concern (local vs majority vs linearizable)?

Write Concern controls the number of replica set members that must commit an insert before returning success (e.g., 'w: majority' prevents data loss during failovers). Read Concern controls isolation: 'local' returns the node's current state immediately, 'majority' returns data acknowledged by most nodes to avoid dirty reads, and 'linearizable' guarantees strictly real-time read ordering across the cluster.

How does the WiredTiger storage engine handle concurrency and compression in MongoDB?

WiredTiger utilizes document-level locking and optimistic concurrency control with hazard pointers, allowing concurrent writes to distinct documents without collection-wide locks. It provides Snappy and Zstandard compression on disk, reducing storage footprint by 60–80% compared to uncompressed BSON.

What is an aggregation pipeline and how do stages ($match, $project, $lookup) stream data?

The aggregation pipeline processes documents through a series of sequential stages. Early filtering with '$match' utilizes indexes to discard irrelevant documents before downstream stages (like '$group', '$lookup', '$sort') transform and project remaining documents in streaming memory buffers.

When should you shard a MongoDB cluster and what makes a good shard key?

Shard when dataset volume exceeds individual server disk storage, write IOPS saturate disk hardware, or RAM cannot hold working set indexes. A good shard key has high cardinality, uniform write distribution across chunks (avoiding monotonically increasing IDs that bottleneck a single shard), and aligns with common query routing filters.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets