DEV Community

Millie Molotov
Millie Molotov

Posted on • Edited on

MongoDB Command Shortcuts: The Ultimate Guide

This post is a comprehensive guide to the most important MongoDB commands and operations. It covers basic queries, CRUD operations, indexing, aggregation, and more advanced concepts.


1. MongoDB Basics

Connecting to MongoDB

mongo --host <hostname> --port <port> -u <username> -p <password> --authenticationDatabase <authDB>
Enter fullscreen mode Exit fullscreen mode

Show Databases

show dbs;
Enter fullscreen mode Exit fullscreen mode

Use a Database

use myDatabase;
Enter fullscreen mode Exit fullscreen mode

Show Collections

show collections;
Enter fullscreen mode Exit fullscreen mode

2. CRUD Operations

Create a Collection

db.createCollection("myCollection");
Enter fullscreen mode Exit fullscreen mode

Insert Documents

db.myCollection.insertOne({ name: "John", age: 30 });
db.myCollection.insertMany([{ name: "Jane", age: 25 }, { name: "Doe", age: 22 }]);
Enter fullscreen mode Exit fullscreen mode

Read Documents

db.myCollection.find();
db.myCollection.find({ name: "John" });
Enter fullscreen mode Exit fullscreen mode

Update Documents

db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } });
db.myCollection.updateMany({ age: { $lt: 30 } }, { $set: { status: "young" } });
Enter fullscreen mode Exit fullscreen mode

Delete Documents

db.myCollection.deleteOne({ name: "John" });
db.myCollection.deleteMany({ age: { $lt: 25 } });
Enter fullscreen mode Exit fullscreen mode

3. Querying Documents

Basic Queries

db.myCollection.find({ name: "John" });
db.myCollection.find({ age: { $gt: 25 } });
Enter fullscreen mode Exit fullscreen mode

Projection

db.myCollection.find({}, { name: 1, age: 1 });
Enter fullscreen mode Exit fullscreen mode

Sorting

db.myCollection.find().sort({ age: -1 });
Enter fullscreen mode Exit fullscreen mode

Limiting and Skipping

db.myCollection.find().limit(5);
db.myCollection.find().skip(5).limit(5);
Enter fullscreen mode Exit fullscreen mode

4. Updating Documents

Update Operators

  • $set: Sets the value of a field
db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } });
Enter fullscreen mode Exit fullscreen mode
  • $unset: Removes a field
db.myCollection.updateOne({ name: "John" }, { $unset: { age: "" } });
Enter fullscreen mode Exit fullscreen mode
  • $inc: Increments the value of a field
db.myCollection.updateOne({ name: "John" }, { $inc: { age: 1 } });
Enter fullscreen mode Exit fullscreen mode
  • $push: Adds an item to an array
db.myCollection.updateOne({ name: "John" }, { $push: { hobbies: "reading" } });
Enter fullscreen mode Exit fullscreen mode

5. Deleting Documents

Delete Operators

  • deleteOne: Deletes a single document
db.myCollection.deleteOne({ name: "John" });
Enter fullscreen mode Exit fullscreen mode
  • deleteMany: Deletes multiple documents
db.myCollection.deleteMany({ age: { $lt: 25 } });
Enter fullscreen mode Exit fullscreen mode

6. Indexes

Creating Indexes

db.myCollection.createIndex({ name: 1 });
Enter fullscreen mode Exit fullscreen mode

Viewing Indexes

db.myCollection.getIndexes();
Enter fullscreen mode Exit fullscreen mode

Dropping Indexes

db.myCollection.dropIndex("name_1");
Enter fullscreen mode Exit fullscreen mode

7. Aggregation

Basic Aggregation

db.myCollection.aggregate([
    { $match: { status: "active" } },
    { $group: { _id: "$age", total: { $sum: 1 } } }
]);
Enter fullscreen mode Exit fullscreen mode

Common Aggregation Stages

  • $match: Filters documents
{ $match: { status: "active" } }
Enter fullscreen mode Exit fullscreen mode
  • $group: Groups documents by a specified field
{ $group: { _id: "$age", total: { $sum: 1 } } }
Enter fullscreen mode Exit fullscreen mode
  • $sort: Sorts documents
{ $sort: { total: -1 } }
Enter fullscreen mode Exit fullscreen mode
  • $project: Reshapes documents
{ $project: { name: 1, age: 1 } }
Enter fullscreen mode Exit fullscreen mode

8. Data Modeling

Embedding Documents

let post = {
    title: "Post Title",
    content: "Post Content",
    comments: [
        { user: "John", comment: "Great post!" },
        { user: "Jane", comment: "Thanks for sharing!" }
    ]
};
Enter fullscreen mode Exit fullscreen mode

Referencing Documents

let user = { name: "John" };
let post = { title: "Post Title", content: "Post Content", userId: user._id };
Enter fullscreen mode Exit fullscreen mode

9. Replication

Setting Up a Replica Set

rs.initiate();
rs.add("mongodb1.example.net:27017");
rs.add("mongodb2.example.net:27017");
rs.add("mongodb3.example.net:27017");
Enter fullscreen mode Exit fullscreen mode

Checking Replica Set Status

rs.status();
Enter fullscreen mode Exit fullscreen mode

10. Sharding

Enabling Sharding

sh.enableSharding("myDatabase");
Enter fullscreen mode Exit fullscreen mode

Sharding a Collection

sh.shardCollection("myDatabase.myCollection", { shardKey: 1 });
Enter fullscreen mode Exit fullscreen mode

11. Transactions

Starting a Transaction

const session = db.getMongo().startSession();
session.startTransaction();
Enter fullscreen mode Exit fullscreen mode

Committing a Transaction

session.commitTransaction();
session.endSession();
Enter fullscreen mode Exit fullscreen mode

Aborting a Transaction

session.abortTransaction();
session.endSession();
Enter fullscreen mode Exit fullscreen mode

12. Security

Creating a User

db.createUser({
    user: "myUser",
    pwd: "myPassword",
    roles: [{ role: "readWrite", db: "myDatabase" }]
});
Enter fullscreen mode Exit fullscreen mode

Authenticating a User

db.auth("myUser", "myPassword");
Enter fullscreen mode Exit fullscreen mode

13. Best Practices

  • Use Indexes: Ensure that your queries are efficient by using indexes.
  • Data Modeling: Choose the right data model (embedding vs. referencing) based on your use case.
  • Backup Regularly: Regularly backup your data to prevent data loss.
  • Monitor Performance: Use monitoring tools to keep an eye on the performance of your MongoDB instance.
  • Secure Your Database: Implement proper authentication and authorization mechanisms.

Conclusion

This post summarizes key concepts, commands, and operations for working with MongoDB. Keep this as a quick reference while you're working with MongoDB!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more