mongosh | Connect to local MongoDB |
mongosh "mongodb://host:27017" | Connect to specific host |
mongosh "mongodb+srv://user:pass@cluster.mongodb.net/db" | Connect to Atlas |
mongosh --username user --password pass | Connect with auth |
show dbs | List databases |
use dbname | Switch/create database |
db | Show current database |
db.dropDatabase() | Drop current database |
show collections | List collections |
db.createCollection("name") | Create collection |
db.collection.drop() | Drop collection |
db.stats() | Database statistics |
db.users.insertOne({ name: "John", age: 30 }) | Insert single document |
db.users.insertMany([
{ name: "John" },
{ name: "Jane" }
]) | Insert multiple documents |
db.users.insertOne({ _id: "custom-id", name: "John" }) | Insert with custom _id |
db.users.find() | Find all documents |
db.users.find({ age: 30 }) | Find with filter |
db.users.findOne({ name: "John" }) | Find single document |
db.users.find({ age: { $gt: 25 } }) | Greater than |
db.users.find({ age: { $gte: 25, $lte: 35 } }) | Range query |
db.users.find({ status: { $in: ["A", "B"] } }) | In array |
db.users.find({ $or: [{ age: 25 }, { status: "A" }] }) | OR condition |
db.users.find({ $and: [{ age: 25 }, { status: "A" }] }) | AND condition |
db.users.find({ name: /^J/ }) | Regex match |
db.users.find({ email: { $exists: true } }) | Field exists |
db.users.find({ tags: "mongodb" }) | Array contains |
db.users.find({ "address.city": "Seoul" }) | Nested field |
db.users.find({}, { name: 1, email: 1 }) | Include fields |
db.users.find({}, { password: 0 }) | Exclude fields |
db.users.find().sort({ age: 1 }) | Sort ascending |
db.users.find().sort({ age: -1 }) | Sort descending |
db.users.find().limit(10) | Limit results |
db.users.find().skip(10).limit(10) | Pagination |
db.users.find().count() | Count documents |
db.users.distinct("status") | Distinct values |
db.users.updateOne(
{ name: "John" },
{ $set: { age: 31 } }
) | Update single document |
db.users.updateMany(
{ status: "A" },
{ $set: { status: "B" } }
) | Update multiple documents |
db.users.updateOne(
{ name: "John" },
{ $inc: { age: 1 } }
) | Increment field |
db.users.updateOne(
{ name: "John" },
{ $unset: { tempField: "" } }
) | Remove field |
db.users.updateOne(
{ name: "John" },
{ $push: { tags: "new" } }
) | Push to array |
db.users.updateOne(
{ name: "John" },
{ $pull: { tags: "old" } }
) | Remove from array |
db.users.updateOne(
{ name: "John" },
{ $addToSet: { tags: "unique" } }
) | Add unique to array |
db.users.replaceOne(
{ name: "John" },
{ name: "John", age: 32, status: "A" }
) | Replace document |
db.users.updateOne(
{ name: "New" },
{ $set: { name: "New", age: 25 } },
{ upsert: true }
) | Upsert |
db.users.deleteOne({ name: "John" }) | Delete single document |
db.users.deleteMany({ status: "inactive" }) | Delete multiple documents |
db.users.deleteMany({}) | Delete all documents |
db.users.findOneAndDelete({ name: "John" }) | Find and delete |
db.orders.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$customer", total: { $sum: "$amount" } } }
]) | Match and group |
db.users.aggregate([
{ $project: { name: 1, year: { $year: "$createdAt" } } }
]) | Project fields |
db.orders.aggregate([
{ $sort: { amount: -1 } },
{ $limit: 5 }
]) | Sort and limit |
db.orders.aggregate([
{ $unwind: "$items" }
]) | Unwind array |
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}}
]) | Join collections |
{ $sum: "$amount" } | Sum values |
{ $avg: "$price" } | Average value |
{ $min: "$date" } | Minimum value |
{ $max: "$date" } | Maximum value |
{ $first: "$name" } | First value |
{ $last: "$name" } | Last value |
{ $push: "$item" } | Push to array |
{ $addToSet: "$tag" } | Add unique to array |
db.users.createIndex({ email: 1 }) | Create ascending index |
db.users.createIndex({ score: -1 }) | Create descending index |
db.users.createIndex({ email: 1 }, { unique: true }) | Create unique index |
db.users.createIndex({ name: 1, age: -1 }) | Compound index |
db.users.createIndex({ bio: "text" }) | Text index |
db.places.createIndex({ location: "2dsphere" }) | Geospatial index |
db.logs.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
) | TTL index |
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { status: "active" } }
) | Partial index |
db.users.getIndexes() | List indexes |
db.users.dropIndex("email_1") | Drop index |
db.users.dropIndexes() | Drop all indexes |
db.createUser({ user: "admin", pwd: "pass", roles: ["readWrite"] }) | Create user |
db.updateUser("admin", { pwd: "newpass" }) | Update user |
db.dropUser("admin") | Drop user |
db.getUsers() | List users |
db.grantRolesToUser("user", ["dbAdmin"]) | Grant roles |
mongodump --db=dbname --out=/backup/ | Backup database |
mongorestore --db=dbname /backup/dbname/ | Restore database |
mongoexport --db=db --collection=col --out=file.json | Export collection |
mongoimport --db=db --collection=col --file=file.json | Import collection |
db.serverStatus() | Server status |
db.currentOp() | Current operations |
db.collection.stats() | Collection statistics |
db.collection.find().explain("executionStats") | Query execution stats |
db.setProfilingLevel(1, { slowms: 100 }) | Enable profiling |
db.system.profile.find() | View slow queries |
db.collection.validate() | Validate collection |
db.repairDatabase() | Repair database |