DEV Community

Harsh Mishra
Harsh Mishra

Posted on

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! 🚀

Top comments (0)