User Tools

Site Tools


web_development:databases:mongodb

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

  • Document: The basic unit of data in MongoDB, stored in BSON (binary JSON).
  • Collection: A group of documents, similar to a table in relational databases.
  • Database: A container for collections.
  • Field: A key-value pair in a document, similar to a column in relational databases.
  • Replica Set: A group of MongoDB servers that maintain the same data, providing redundancy and high availability.

Basic Commands

  • Show Databases:

```

  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.

  • Simple Aggregation:

```

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

Indexes

Indexes improve query performance.

  • Create an Index:

```

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

Replica Sets

To enable high availability:

  • Initiate a Replica Set:

```

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

Backup and Restore

  • Backup a Database:

```

  mongodump --db <database_name> --out <backup_directory>
  ```
* **Restore a Dat
web_development/databases/mongodb.txt · Last modified: 2025/02/19 08:44 by 195.53.121.100