MongoDB Cheatsheet

Introduction

MongoDB is a NoSQL, document-oriented database that stores data in flexible, JSON-like documents. It is designed for scalability, high availability, and developer ease of use.

Key Concepts

Basic Commands

```

  show dbs
  ```
* **Switch to Database**:
  ```
  use <database_name>
  ```
* **Show Collections**:
  ```
  show collections
  ```
* **Insert a Document**:
  ```
  db.collection.insert({ "key": "value" })
  ```
* **Find Documents**:
  ```
  db.collection.find()
  ```
* **Find with Filter**:
  ```
  db.collection.find({ "key": "value" })
  ```
* **Update a Document**:
  ```
  db.collection.update({ "key": "value" }, { $set: { "key": "new_value" } })
  ```
* **Delete a Document**:
  ```
  db.collection.remove({ "key": "value" })
  ```

Aggregation

MongoDB provides aggregation operations for advanced data processing.

```

  db.collection.aggregate([{ $match: { "key": "value" } }])
  ```
* **Grouping Data**:
  ```
  db.collection.aggregate([
    { $group: { _id: "$field", total: { $sum: 1 } } }
  ])
  ```

Indexes

Indexes improve query performance.

```

  db.collection.createIndex({ "key": 1 })
  ```
* **Drop an Index**:
  ```
  db.collection.dropIndex({ "key": 1 })
  ```

Replica Sets

To enable high availability:

```

  rs.initiate()
  ```
* **Add a Member**:
  ```
  rs.add("hostname:port")
  ```

Backup and Restore

```

  mongodump --db <database_name> --out <backup_directory>
  ```
* **Restore a Dat