db.dropDatabase()destroysDelete the active database entirely.
db.createCollection("name")Explicit create — usually only needed for options.db.createCollection("logs", {capped:true, size:1e6})Fixed-size collection, oldest docs auto-evicted.db.coll.renameCollection("newName")Rename in place.db.coll.drop()destroysDelete the collection + all its documents & indexes.
db.coll.insertOne({name:"Max"})★Insert a single document.db.coll.insertMany([{...},{...}])★Insert many — ordered by default, stops on first error.db.coll.insertMany([...], {ordered:false})Unordered — keeps inserting after individual failures.db.coll.insertOne({date: ISODate()})Use ISODate(), never a plain string, for dates.
db.coll.find()★Every document — returns a cursor.db.coll.find({status:"A"})★Documents matching an exact field filter.db.coll.findOne({status:"A"})★First match only, as a single document (or null).db.coll.find().pretty()Formatted, indented output (mongosh formats by default).db.coll.countDocuments({status:"A"})★Accurate count — runs an aggregation.db.coll.estimatedDocumentCount()Fast count from collection metadata, unfiltered.
{age: {$gt: 25, $lte: 40}}★Comparison: $gt $gte $lt $lte $ne $eq.{status: {$in: ["A","D"]}}★Match any value in a list — also $nin.{$and: [{a:1}, {b:2}]}Combine conditions — also $or, $nor, $not.{email: {$exists: true}}Field is present (or absent with false).db.coll.find({name: /^Max/})★Regex match — append /i for case-insensitive.{tags: {$all: ["a","b"]}}Array contains every listed value.{"items.qty": {$elemMatch: {$gt:5}}}At least one array element satisfies all conditions.
db.coll.find({}, {name:1, age:1})★Include only these fields (+ _id by default).db.coll.find({}, {name:1, _id:0})★Include a field, explicitly drop _id.db.coll.find({}, {password:0})Exclude a field, keep everything else.db.coll.find({}, {tags: {$slice: 3}})Return only the first 3 elements of an array field.
db.coll.find().sort({age: 1})★Ascending — use -1 for descending.db.coll.find().sort({age: -1}).limit(10)★Top 10 oldest, cheapest way to paginate page 1.db.coll.find().skip(20).limit(10)Page 3 of 10-doc pages — skip cost grows with offset.db.coll.find().sort({score:1}).limit(1)Cursor methods chain in any order; execution order is fixed.
{$set: {status: "done"}}★Set (or add) one or more fields.{$unset: {tempField: ""}}Remove a field entirely.{$inc: {views: 1}}★Increment (or decrement with a negative) a number.{$push: {tags: "new"}}★Append to an array field.{$addToSet: {tags: "new"}}Push only if not already present.{$pull: {tags: "old"}}Remove all matching elements from an array.
db.coll.updateOne({_id:1}, {$set:{a:1}})★Update the first matching document.db.coll.updateMany({status:"A"}, {$set:{a:1}})★Update every matching document.db.coll.updateOne({e:"x"}, {$set:{n:1}}, {upsert:true})★Update if found, insert a new doc if not.db.coll.replaceOne({_id:1}, {a:1,b:2})Swap the whole document body (except _id).db.coll.updateOne({_id:1}, {year:2016})no operatorNo $ operator = replaces the entire document.db.coll.findOneAndUpdate({...}, {$set:{...}}, {returnDocument:"after"})Update + return the modified document in one call.
db.coll.deleteOne({name:"Max"})★Delete the first matching document.db.coll.deleteMany({status:"expired"})★Delete every matching document.db.coll.deleteMany({})no filterDeletes every document — collection & indexes remain.db.coll.findOneAndDelete({name:"Max"})Delete + return the removed document.
{$match: {status:"A"}}★Filter documents — same syntax as find().{$group: {_id:"$cust", total:{$sum:"$amt"}}}★Bucket by expression, accumulate per group.{$sort: {total: -1}}★Order the pipeline's current documents.{$project: {name:1, total:1}}Reshape / compute output fields.{$lookup: {from:"orders", localField:"_id", foreignField:"userId", as:"orders"}}★Left-outer join with another collection.{$unwind: "$tags"}One output document per array element.{$limit: 5} · {$skip: 10}Cap results / page through them.
db.coll.createIndex({email: 1})★Single-field index, ascending.db.coll.createIndex({email: 1}, {unique:true})★Index that also enforces uniqueness.db.coll.createIndex({last:1, first:1})Compound index — field order matters.db.coll.createIndex({createdAt:1}, {expireAfterSeconds:86400})TTL index — auto-deletes old documents.db.coll.dropIndex("email_1")careRemove an index — reads slow down.
Core
| ObjectId | 12-byte id, first 4 bytes = creation time |
| String | UTF-8 text |
| Boolean | true / false |
| Null | explicit "no value" |
| Array / Object | nested lists & embedded documents |
Numeric
| Int32 / NumberInt | standard 32-bit integer |
| NumberLong | 64-bit — use for big counters/ids |
| Double | default JS number, floating point |
| NumberDecimal | exact decimal — use for money |
Date & Time
| Date / ISODate() | ms since epoch — sortable, comparable |
| Timestamp | internal, used by the oplog |
Other
| Binary | raw bytes / files (small ones) |
| Regex | a stored regular expression |
| GeoJSON | Point/Polygon for geospatial queries |
db.createCollection("users", {validator: {$jsonSchema: {...}}})★Enforce field types/required on insert & update.{bsonType:"string", minLength:1}Type + constraint rule inside a schema.db.runCommand({collMod:"users", validator:{...}})Attach/replace validation on an existing collection.{validationLevel: "moderate"}strict = all writes checked; moderate = only valid docs stay valid.
const session = db.getMongo().startSession()★Open a session to scope the transaction.session.startTransaction()★Begin an atomic block across collections/docs.session.commitTransaction()★Make every write in the block permanent.session.abortTransaction()Roll back everything since the start.
db.createUser({user:"u", pwd:"pw", roles:["readWrite"]})★Create a user scoped to the active database.db.getUsers()List users on the active database.db.grantRolesToUser("u", ["dbAdmin"])Add roles to an existing user.db.revokeRolesFromUser("u", ["dbAdmin"])Remove specific roles.db.dropUser("u")destroysDelete the account entirely.
mongodump --db=mydb --out=./backup★Export a database to BSON files.mongorestore --db=mydb ./backup/mydb★Restore a BSON dump into a database.mongoexport --collection=users --out=u.jsonExport one collection to JSON/CSV.mongoimport --collection=users --file=u.jsonBulk-load a JSON/CSV file into a collection.
rs.status()★Health & role of every replica set member.rs.initiate({...})Bootstrap a new replica set.rs.add("host:27017")Add a node to the replica set.sh.status()Shard cluster overview.sh.shardCollection("db.coll", {key:1})Enable sharding on a collection by a shard key.
$eq $ne $gt $gte $lt $lteComparison, inside a query filter.$and $or $not $norLogical combinators for filters.$set $unset $inc $renameField-level update operators.$push $pull $addToSet $popArray update operators.$sum $avg $min $max $pushAccumulators, used inside $group.