100 MongoDB Commands for Mastering MongoDB

100 MongoDB Commands

100 MongoDB Commands for Mastering MongoDB

Database Creation and Management

  1. Show Databases:
    show dbs;
  2. Create or Switch Database:
    use myDatabase;
  3. Drop Database:
    db.dropDatabase();
  4. Get Current Database:
    db.getName();

Collection Creation and Management

  1. Create Collection:
    db.createCollection("users");
  2. Show Collections:
    show collections;
  3. Drop Collection:
    db.users.drop();

Basic Data Operations

  1. Insert One Document:
    db.users.insertOne({ name: "John Doe", email: "john@example.com" });
  2. Insert Many Documents:
    db.users.insertMany([{ name: "Jane Doe", email: "jane@example.com" }, { name: "Sam Smith", email: "sam@example.com" }]);
  3. Find One Document:
    db.users.findOne({ name: "John Doe" });
  4. Find All Documents:
    db.users.find();
  5. Update One Document:
    db.users.updateOne({ name: "John Doe" }, { $set: { email: "john.doe@example.com" } });
  6. Update Many Documents:
    db.users.updateMany({ name: { $regex: /^J/ } }, { $set: { verified: true } });
  7. Replace One Document:
    db.users.replaceOne({ name: "John Doe" }, { name: "John Doe", email: "john.doe@example.com", age: 30 });
  8. Delete One Document:
    db.users.deleteOne({ name: "John Doe" });
  9. Delete Many Documents:
    db.users.deleteMany({ verified: false });

Query Operators

  1. 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 } });
  2. 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 }] });
  3. Element Operators:
    db.users.find({ age: { $exists: true } });
    db.users.find({ name: { $type: "string" } });
  4. 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 } } } });
  5. Evaluation Operators:
    db.users.find({ $expr: { $gt: ["$age", "$yearsEmployed"] } });
    db.users.find({ name: { $regex: /^J/, $options: "i" } });

Indexes

  1. Create Index:
    db.users.createIndex({ name: 1 });
  2. Drop Index:
    db.users.dropIndex("name_1");
  3. Show Indexes:
    db.users.getIndexes();

Aggregation

  1. Simple Aggregation:
    db.users.aggregate([{ $match: { age: { $gt: 25 } } }]);
  2. Group Aggregation:
    db.users.aggregate([{ $group: { _id: "$age", total: { $sum: 1 } } }]);
  3. Sort Aggregation:
    db.users.aggregate([{ $sort: { age: -1 } }]);
  4. Limit Aggregation:
    db.users.aggregate([{ $limit: 5 } }]);
  5. Project Aggregation:
    db.users.aggregate([{ $project: { name: 1, age: 1 } }]);
  6. Unwind Aggregation:
    db.users.aggregate([{ $unwind: "$interests" }]);

Backup and Restore

  1. Backup Database:
    mongodump --db myDatabase --out /backup/myDatabase
  2. Restore Database:
    mongorestore /backup/myDatabase

User Management

  1. Create User:
    db.createUser({ user: "admin", pwd: "password", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] });
  2. Drop User:
    db.dropUser("admin");
  3. Grant Role to User:
    db.grantRolesToUser("admin", [{ role: "readWrite", db: "myDatabase" }]);
  4. Revoke Role from User:
    db.revokeRolesFromUser("admin", [{ role: "readWrite", db: "myDatabase" }]);

Data Modeling

  1. Schema Design:
    db.users.insertOne({ name: "John Doe", email: "john@example.com", profile: { age: 30, gender: "male" }, interests: ["reading", "music"] });
  2. Embed Data:
    db.orders.insertOne({ user_id: ObjectId("..."), items: [{ product_id: ObjectId("..."), quantity: 2 }] });
  3. Reference Data:
    db.orders.insertOne({ user_id: ObjectId("..."), items: [ObjectId("..."), ObjectId("...")] });

Text Search

  1. Create Text Index:
    db.users.createIndex({ name: "text", bio: "text" });
  2. Text Search:
    db.users.find({ $text: { $search: "John" } });

Geospatial Queries

  1. Create Geospatial Index:
    db.places.createIndex({ location: "2dsphere" });
  2. Geospatial Query:
    db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $maxDistance: 1000 } } });

Server Administration

  1. Server Status:
    db.serverStatus();
  2. Database Stats:
    db.stats();
  3. Collection Stats:
    db.users.stats();

Sharding

  1. Enable Sharding:
    sh.enableSharding("myDatabase");
  2. Shard Collection:
    sh.shardCollection("myDatabase.users", { _id: 1 });
  3. Add Shard:
    sh.addShard("shard0000/localhost:27018");
  4. Remove Shard:
    sh.removeShard("shard0000");

Replica Sets

  1. Initiate Replica Set:
    rs.initiate();
  2. Add Member to Replica Set:
    rs.add("mongodb1.example.net:27017");
  3. Remove Member from Replica Set:
    rs.remove("mongodb1.example.net:27017");
  4. Reconfigure Replica Set:
    rs.reconfig(cfg);

Sessions

  1. Start Session:
    session = db.getMongo().startSession();
  2. End Session:
    session.endSession();

Transactions

  1. Start Transaction:
    session.startTransaction();
  2. Commit Transaction:
    session.commitTransaction();
  3. Abort Transaction:
    session.abortTransaction();

Change Streams

  1. Watch Change Stream:
    db.users.watch();
  2. Filter Change Stream:
    db.users.watch([{ $match: { operationType: "insert" } }]);

File Storage

  1. Store File in GridFS:
    var bucket = new Mongo().getBucket();
    bucket.uploadFromStream("myFile.txt", fs.createReadStream("/path/to/file.txt"));
  2. Retrieve File from GridFS:
    var bucket = new Mongo().getBucket();
    bucket.openDownloadStreamByName("myFile.txt").pipe(fs.createWriteStream("/path/to/output.txt"));

Security

  1. Enable Authentication:
    // Add "--auth" flag to MongoDB server startup
  2. Enable SSL:
    // Add "--sslMode requireSSL --sslPEMKeyFile /path/to/cert.pem" to MongoDB server startup

Miscellaneous

  1. Rename Collection:
    db.users.renameCollection("customers");
  2. Clone Database:
    db.cloneDatabase("sourceHost");
  3. Copy Database:
    db.copyDatabase("sourceDb", "targetDb", "sourceHost");

Administrative Commands

  1. Run Command:
    db.runCommand({ buildInfo: 1 });
  2. Profile Database:
    db.setProfilingLevel(2);
  3. Get Profiling Level:
    db.getProfilingLevel();
  4. Log Messages:
    db.adminCommand({ getLog: "global" });
  5. Current Operations:
    db.currentOp();
  6. Kill Operation:
    db.killOp(opid);

Export and Import

  1. Export Collection:
    mongoexport --db myDatabase --collection users --out users.json
  2. Import Collection:
    mongoimport --db myDatabase --collection users --file users.json

Aggregation Pipelines

  1. Match Stage:
    db.users.aggregate([{ $match: { age: { $gt: 25 } } }]);
  2. Group Stage:
    db.users.aggregate([{ $group: { _id: "$age", count: { $sum: 1 } } }]);
  3. Sort Stage:
    db.users.aggregate([{ $sort: { age: 1 } }]);
  4. Project Stage:
    db.users.aggregate([{ $project: { name: 1, age: 1 } }]);
  5. Limit Stage:
    db.users.aggregate([{ $limit: 10 }]);
  6. Unwind Stage:
    db.users.aggregate([{ $unwind: "$interests" }]);
  7. Lookup Stage:
    db.orders.aggregate([{ $lookup: { from: "users", localField: "user_id", foreignField: "_id", as: "user" } }]);

Field Update Operators

  1. Increment Field:
    db.users.updateOne({ name: "John Doe" }, { $inc: { age: 1 } });
  2. Multiply Field:
    db.users.updateOne({ name: "John Doe" }, { $mul: { age: 2 } });
  3. Rename Field:
    db.users.updateOne({ name: "John Doe" }, { $rename: { "oldName": "newName" } });
  4. Set Field:
    db.users.updateOne({ name: "John Doe" }, { $set: { age: 30 } });
  5. Unset Field:
    db.users.updateOne({ name: "John Doe" }, { $unset: { age: "" } });

Array Update Operators

  1. Add to Array:
    db.users.updateOne({ name: "John Doe" }, { $push: { interests: "swimming" } });
  2. Remove from Array:
    db.users.updateOne({ name: "John Doe" }, { $pull: { interests: "swimming" } });
  3. Pop from Array:
    db.users.updateOne({ name: "John Doe" }, { $pop: { interests: 1 } });
  4. Add to Set (Array):
    db.users.updateOne({ name: "John Doe" }, { $addToSet: { interests: "swimming" } });
  5. Pull All from Array:
    db.users.updateOne({ name: "John Doe" }, { $pullAll: { interests: ["swimming", "reading"] } });

Data Validation

  1. 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"
                    }
                }
            }
        }
    });
  2. 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

  1. Compact Collection:
    db.runCommand({ compact: "users" });
  2. Repair Database:
    db.repairDatabase();

Advanced Indexing

  1. Create Compound Index:
    db.users.createIndex({ name: 1, email: -1 });
  2. Create TTL Index:
    db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });
  3. 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.

Back To Top