DEV Community

Harsh Mishra
Harsh Mishra

Posted on

1

MongoDB Commands Categorized

The Ultimate List of MongoDB Commands Categorized by Usage

MongoDB is a powerful NoSQL database known for its flexibility and scalability. Whether you are a beginner or an advanced user, mastering MongoDB commands will help you efficiently manage databases, collections, and documents. This guide categorizes MongoDB commands based on their usage, covering everything from basic operations to advanced database management.


1. Basic MongoDB Commands

Starting and Stopping MongoDB

  • Start MongoDB:
  sudo systemctl start mongod
Enter fullscreen mode Exit fullscreen mode
  • Stop MongoDB:
  sudo systemctl stop mongod
Enter fullscreen mode Exit fullscreen mode
  • Restart MongoDB:
  sudo systemctl restart mongod
Enter fullscreen mode Exit fullscreen mode
  • Check MongoDB status:
  sudo systemctl status mongod
Enter fullscreen mode Exit fullscreen mode

Connecting to MongoDB

  • Open MongoDB shell:
  mongo
Enter fullscreen mode Exit fullscreen mode
  • Connect to a specific database:
  use <database_name>
Enter fullscreen mode Exit fullscreen mode
  • Show available databases:
  show dbs
Enter fullscreen mode Exit fullscreen mode
  • Show the currently selected database:
  db
Enter fullscreen mode Exit fullscreen mode

2. Database Management

Creating a Database

MongoDB automatically creates a database when a document is inserted. However, you can explicitly select a database:

use myDatabase
Enter fullscreen mode Exit fullscreen mode

(This does not create the database until data is added.)

Dropping a Database

db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Deletes the currently selected database.

Listing All Databases

show dbs
Enter fullscreen mode Exit fullscreen mode

Displays all available databases.

Checking the Current Database

db
Enter fullscreen mode Exit fullscreen mode

Displays the name of the currently selected database.


3. Collection Management

Creating a Collection

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

Creates an empty collection.

Listing All Collections

show collections
Enter fullscreen mode Exit fullscreen mode

Displays all collections in the current database.

Dropping a Collection

db.myCollection.drop()
Enter fullscreen mode Exit fullscreen mode

Deletes a specific collection.


4. Document Management (CRUD Operations)

Inserting Documents

  • Insert a single document:
  db.myCollection.insertOne({ name: "Alice", age: 25, city: "New York" })
Enter fullscreen mode Exit fullscreen mode
  • Insert multiple documents:
  db.myCollection.insertMany([
      { name: "Bob", age: 30, city: "Los Angeles" },
      { name: "Charlie", age: 35, city: "Chicago" }
  ])
Enter fullscreen mode Exit fullscreen mode

Reading Documents (Querying)

  • Find all documents in a collection:
  db.myCollection.find()
Enter fullscreen mode Exit fullscreen mode
  • Find a specific document:
  db.myCollection.findOne({ name: "Alice" })
Enter fullscreen mode Exit fullscreen mode
  • Find documents with specific conditions:
  db.myCollection.find({ age: { $gt: 30 } })
Enter fullscreen mode Exit fullscreen mode

Finds all documents where age is greater than 30.

  • Projection (return only specific fields):
  db.myCollection.find({ }, { name: 1, _id: 0 })
Enter fullscreen mode Exit fullscreen mode

Returns only the name field and excludes _id.

Updating Documents

  • Update a single document:
  db.myCollection.updateOne(
      { name: "Alice" },
      { $set: { age: 26 } }
  )
Enter fullscreen mode Exit fullscreen mode
  • Update multiple documents:
  db.myCollection.updateMany(
      { city: "New York" },
      { $set: { country: "USA" } }
  )
Enter fullscreen mode Exit fullscreen mode
  • Replace a document:
  db.myCollection.replaceOne(
      { name: "Alice" },
      { name: "Alice", age: 27, city: "Boston" }
  )
Enter fullscreen mode Exit fullscreen mode

Deleting Documents

  • Delete a single document:
  db.myCollection.deleteOne({ name: "Alice" })
Enter fullscreen mode Exit fullscreen mode
  • Delete multiple documents:
  db.myCollection.deleteMany({ city: "Los Angeles" })
Enter fullscreen mode Exit fullscreen mode

5. Indexing and Performance Optimization

Creating Indexes

  • Create an index on a field:
  db.myCollection.createIndex({ name: 1 })
Enter fullscreen mode Exit fullscreen mode
  • Create a compound index:
  db.myCollection.createIndex({ name: 1, age: -1 })
Enter fullscreen mode Exit fullscreen mode
  • Create a unique index:
  db.myCollection.createIndex({ email: 1 }, { unique: true })
Enter fullscreen mode Exit fullscreen mode

Listing Indexes

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

Dropping an Index

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

6. Aggregation Framework

Using Aggregation Pipelines

  • Count documents in a collection:
  db.myCollection.countDocuments()
Enter fullscreen mode Exit fullscreen mode
  • Group and count by a field:
  db.myCollection.aggregate([
      { $group: { _id: "$city", count: { $sum: 1 } } }
  ])
Enter fullscreen mode Exit fullscreen mode
  • Sort documents:
  db.myCollection.aggregate([
      { $sort: { age: -1 } }
  ])
Enter fullscreen mode Exit fullscreen mode

7. User and Role Management

Creating a User

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

Listing Users

db.getUsers()
Enter fullscreen mode Exit fullscreen mode

Deleting a User

db.dropUser("adminUser")
Enter fullscreen mode Exit fullscreen mode

8. Backup and Restore

Backup a Database

mongodump --db myDatabase --out /backup/
Enter fullscreen mode Exit fullscreen mode

Restore a Database

mongorestore --db myDatabase /backup/myDatabase/
Enter fullscreen mode Exit fullscreen mode

9. Replica Sets and Sharding

Checking Replica Set Status

rs.status()
Enter fullscreen mode Exit fullscreen mode

Initiating a Replica Set

rs.initiate()
Enter fullscreen mode Exit fullscreen mode

Adding a Member to a Replica Set

rs.add("mongodb2.example.com:27017")
Enter fullscreen mode Exit fullscreen mode

Sharding a Collection

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

10. Server Administration and Monitoring

Checking MongoDB Server Status

db.serverStatus()
Enter fullscreen mode Exit fullscreen mode

Checking Database Stats

db.stats()
Enter fullscreen mode Exit fullscreen mode

Checking Collection Stats

db.myCollection.stats()
Enter fullscreen mode Exit fullscreen mode

Logging Slow Queries

db.setProfilingLevel(1)
Enter fullscreen mode Exit fullscreen mode

Enabling Authorization

Edit /etc/mongod.conf and add:

security:
  authorization: enabled
Enter fullscreen mode Exit fullscreen mode

Restart MongoDB:

sudo systemctl restart mongod
Enter fullscreen mode Exit fullscreen mode

Conclusion

This guide provides a categorized reference for essential MongoDB commands. Whether you are working with collections, queries, indexes, or replication, these commands will help you efficiently manage MongoDB databases. Keep this guide handy as a quick reference! ๐Ÿš€

Quadratic AI

Quadratic AI โ€“ The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo ๐Ÿ“Šโœจ

Top comments (0)

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong ยท web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video ๐ŸŒถ๏ธ๐Ÿ”ฅ

๐Ÿ‘‹ Kindness is contagious

If you found this article helpful, please give a โค๏ธ or share a friendly comment!

Got it