100 MongoDB Commands for Mastering MongoDB
Database Creation and Management
- Show Databases:
show dbs; - Create or Switch Database:
use myDatabase; - Drop Database:
db.dropDatabase(); - Get Current Database:
db.getName();
Collection Creation and Management
- Create Collection:
db.createCollection("users"); - Show Collections:
show collections; - Drop Collection:
db.users.drop();
Basic Data Operations
- Insert One Document:
db.users.insertOne({ name: "John Doe", email: "john@example.com" }); - Insert Many Documents:
db.users.insertMany([{ name: "Jane Doe", email: "jane@example.com" }, { name: "Sam Smith", email: "sam@example.com" }]); - Find One Document:
db.users.findOne({ name: "John Doe" }); - Find All Documents:
db.users.find(); - Update One Document:
db.users.updateOne({ name: "John Doe" }, { $set: { email: "john.doe@example.com" } }); - Update Many Documents:
db.users.updateMany({ name: { $regex: /^J/ } }, { $set: { verified: true } }); - Replace One Document:
db.users.replaceOne({ name: "John Doe" }, { name: "John Doe", email: "john.doe@example.com", age: 30 }); - Delete One Document:
db.users.deleteOne({ name: "John Doe" }); - Delete Many Documents:
db.users.deleteMany({ verified: false });
Query Operators
- Comparison Operators:
db.users.find({ age: { $gt: 25 } }); db.users.find({ age: { $gte: 25 } }); db.users.find({ age: { $lt: 25 } }); db.users.find({ age: { $lte: 25 } }); db.users.find({ age: { $eq: 25 } }); db.users.find({ age: { $ne: 25 } }); - Logical Operators:
db.users.find({ $and: [{ age: { $gt: 25 } }, { verified: true }] }); db.users.find({ $or: [{ age: { $gt: 25 } }, { verified: true }] }); db.users.find({ $not: { age: { $gt: 25 } } }); db.users.find({ $nor: [{ age: { $gt: 25 } }, { verified: true }] }); - Element Operators:
db.users.find({ age: { $exists: true } }); db.users.find({ name: { $type: "string" } }); - Array Operators:
db.users.find({ interests: { $all: ["reading", "music"] } }); db.users.find({ interests: { $size: 3 } }); db.users.find({ interests: { $elemMatch: { name: "reading", level: { $gt: 5 } } } }); - Evaluation Operators:
db.users.find({ $expr: { $gt: ["$age", "$yearsEmployed"] } }); db.users.find({ name: { $regex: /^J/, $options: "i" } });
Indexes
- Create Index:
db.users.createIndex({ name: 1 }); - Drop Index:
db.users.dropIndex("name_1"); - Show Indexes:
db.users.getIndexes();
Aggregation
- Simple Aggregation:
db.users.aggregate([{ $match: { age: { $gt: 25 } } }]); - Group Aggregation:
db.users.aggregate([{ $group: { _id: "$age", total: { $sum: 1 } } }]); - Sort Aggregation:
db.users.aggregate([{ $sort: { age: -1 } }]); - Limit Aggregation:
db.users.aggregate([{ $limit: 5 } }]); - Project Aggregation:
db.users.aggregate([{ $project: { name: 1, age: 1 } }]); - Unwind Aggregation:
db.users.aggregate([{ $unwind: "$interests" }]);
Backup and Restore
- Backup Database:
mongodump --db myDatabase --out /backup/myDatabase - Restore Database:
mongorestore /backup/myDatabase
User Management
- Create User:
db.createUser({ user: "admin", pwd: "password", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] }); - Drop User:
db.dropUser("admin"); - Grant Role to User:
db.grantRolesToUser("admin", [{ role: "readWrite", db: "myDatabase" }]); - Revoke Role from User:
db.revokeRolesFromUser("admin", [{ role: "readWrite", db: "myDatabase" }]);
Data Modeling
- Schema Design:
db.users.insertOne({ name: "John Doe", email: "john@example.com", profile: { age: 30, gender: "male" }, interests: ["reading", "music"] }); - Embed Data:
db.orders.insertOne({ user_id: ObjectId("..."), items: [{ product_id: ObjectId("..."), quantity: 2 }] }); - Reference Data:
db.orders.insertOne({ user_id: ObjectId("..."), items: [ObjectId("..."), ObjectId("...")] });
Text Search
- Create Text Index:
db.users.createIndex({ name: "text", bio: "text" }); - Text Search:
db.users.find({ $text: { $search: "John" } });
Geospatial Queries
- Create Geospatial Index:
db.places.createIndex({ location: "2dsphere" }); - Geospatial Query:
db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $maxDistance: 1000 } } });
Server Administration
- Server Status:
db.serverStatus(); - Database Stats:
db.stats(); - Collection Stats:
db.users.stats();
Sharding
- Enable Sharding:
sh.enableSharding("myDatabase"); - Shard Collection:
sh.shardCollection("myDatabase.users", { _id: 1 }); - Add Shard:
sh.addShard("shard0000/localhost:27018"); - Remove Shard:
sh.removeShard("shard0000");
Replica Sets
- Initiate Replica Set:
rs.initiate(); - Add Member to Replica Set:
rs.add("mongodb1.example.net:27017"); - Remove Member from Replica Set:
rs.remove("mongodb1.example.net:27017"); - Reconfigure Replica Set:
rs.reconfig(cfg);
Sessions
- Start Session:
session = db.getMongo().startSession(); - End Session:
session.endSession();
Transactions
- Start Transaction:
session.startTransaction(); - Commit Transaction:
session.commitTransaction(); - Abort Transaction:
session.abortTransaction();
Change Streams
- Watch Change Stream:
db.users.watch(); - Filter Change Stream:
db.users.watch([{ $match: { operationType: "insert" } }]);
File Storage
- Store File in GridFS:
var bucket = new Mongo().getBucket(); bucket.uploadFromStream("myFile.txt", fs.createReadStream("/path/to/file.txt")); - Retrieve File from GridFS:
var bucket = new Mongo().getBucket(); bucket.openDownloadStreamByName("myFile.txt").pipe(fs.createWriteStream("/path/to/output.txt"));
Security
- Enable Authentication:
// Add "--auth" flag to MongoDB server startup - Enable SSL:
// Add "--sslMode requireSSL --sslPEMKeyFile /path/to/cert.pem" to MongoDB server startup
Miscellaneous
- Rename Collection:
db.users.renameCollection("customers"); - Clone Database:
db.cloneDatabase("sourceHost"); - Copy Database:
db.copyDatabase("sourceDb", "targetDb", "sourceHost");
Administrative Commands
- Run Command:
db.runCommand({ buildInfo: 1 }); - Profile Database:
db.setProfilingLevel(2); - Get Profiling Level:
db.getProfilingLevel(); - Log Messages:
db.adminCommand({ getLog: "global" }); - Current Operations:
db.currentOp(); - Kill Operation:
db.killOp(opid);
Export and Import
- Export Collection:
mongoexport --db myDatabase --collection users --out users.json - Import Collection:
mongoimport --db myDatabase --collection users --file users.json
Aggregation Pipelines
- Match Stage:
db.users.aggregate([{ $match: { age: { $gt: 25 } } }]); - Group Stage:
db.users.aggregate([{ $group: { _id: "$age", count: { $sum: 1 } } }]); - Sort Stage:
db.users.aggregate([{ $sort: { age: 1 } }]); - Project Stage:
db.users.aggregate([{ $project: { name: 1, age: 1 } }]); - Limit Stage:
db.users.aggregate([{ $limit: 10 }]); - Unwind Stage:
db.users.aggregate([{ $unwind: "$interests" }]); - Lookup Stage:
db.orders.aggregate([{ $lookup: { from: "users", localField: "user_id", foreignField: "_id", as: "user" } }]);
Field Update Operators
- Increment Field:
db.users.updateOne({ name: "John Doe" }, { $inc: { age: 1 } }); - Multiply Field:
db.users.updateOne({ name: "John Doe" }, { $mul: { age: 2 } }); - Rename Field:
db.users.updateOne({ name: "John Doe" }, { $rename: { "oldName": "newName" } }); - Set Field:
db.users.updateOne({ name: "John Doe" }, { $set: { age: 30 } }); - Unset Field:
db.users.updateOne({ name: "John Doe" }, { $unset: { age: "" } });
Array Update Operators
- Add to Array:
db.users.updateOne({ name: "John Doe" }, { $push: { interests: "swimming" } }); - Remove from Array:
db.users.updateOne({ name: "John Doe" }, { $pull: { interests: "swimming" } }); - Pop from Array:
db.users.updateOne({ name: "John Doe" }, { $pop: { interests: 1 } }); - Add to Set (Array):
db.users.updateOne({ name: "John Doe" }, { $addToSet: { interests: "swimming" } }); - Pull All from Array:
db.users.updateOne({ name: "John Doe" }, { $pullAll: { interests: ["swimming", "reading"] } });
Data Validation
- Create Validator:
db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "email"], properties: { name: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType: "string", pattern: "^.+@.+$", description: "must be a valid email and is required" } } } } }); - Update Validator:
db.runCommand({ collMod: "users", validator: { $jsonSchema: { bsonType: "object", required: ["name", "email"], properties: { name: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType: "string", pattern: "^.+@.+$", description: "must be a valid email and is required" } } } } });
Server Maintenance
- Compact Collection:
db.runCommand({ compact: "users" }); - Repair Database:
db.repairDatabase();
Advanced Indexing
- Create Compound Index:
db.users.createIndex({ name: 1, email: -1 }); - Create TTL Index:
db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }); - Create Partial Index:
db.users.createIndex({ name: 1 }, { partialFilterExpression: { age: { $gt: 21 } } });
Mastering these 100 MongoDB commands will give you a comprehensive understanding of how to effectively manage and manipulate your MongoDB databases.
