Top 10 MongoDB Commands Every Developer Should Know

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. Whether you’re a beginner or an experienced developer, mastering key MongoDB commands will help you work efficiently. This guide covers the top 10 essential commands every developer should know.


1️⃣ Connect to MongoDB

To start using MongoDB, you need to connect to it using the MongoDB shell (mongosh).

mongosh "mongodb://localhost:27017"

For authentication:

mongosh "mongodb://username:password@localhost:27017/dbname"

2️⃣ Show All Databases

To see the available databases in your MongoDB instance:

show dbs

3️⃣ Create or Switch to a Database

To create a new database (or switch to an existing one):

use myDatabase

MongoDB creates the database automatically when you insert data into it.


4️⃣ Show Collections

To list all collections (tables) in the current database:

show collections

5️⃣ Insert Documents

To add data to a collection, use insertOne or insertMany.

db.students.insertOne({ name: "Alice", age: 22, class: "Math 101" })
db.students.insertMany([
  { name: "Bob", age: 25, class: "Physics" },
  { name: "Charlie", age: 23, class: "History" }
])

6️⃣ Find Documents

To retrieve documents from a collection, use findOne or find.

db.students.findOne({ name: "Alice" })
db.students.find({ age: { $gt: 22 } })

To format the output:

db.students.find().pretty()

7️⃣ Update Documents

To modify an existing document, use updateOne or updateMany.

db.students.updateOne(
  { name: "Alice" },
  { $set: { age: 23 } }
)
db.students.updateMany(
  { class: "Math 101" },
  { $set: { status: "Active" } }
)

8️⃣ Delete Documents

To remove documents, use deleteOne or deleteMany.

db.students.deleteOne({ name: "Alice" })
db.students.deleteMany({ age: { $gt: 24 } })

9️⃣ Create an Index

Indexes improve query performance. To create an index on a field:

db.students.createIndex({ name: 1 })

To view existing indexes:

db.students.getIndexes()

🔟 Aggregate Data

MongoDB's aggregation framework helps process data efficiently.

db.students.aggregate([
  { $group: { _id: "$class", totalStudents: { $sum: 1 } } }
])

Conclusion

Mastering these MongoDB commands will help you navigate databases, manage data, and optimize queries efficiently. Whether you’re inserting data, retrieving documents, or aggregating results, these commands will be essential in your MongoDB journey!

Happy coding!