> ## Documentation Index
> Fetch the complete documentation index at: https://docs.spojit.com/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB

> Query documents, run aggregations, and manage collections in MongoDB databases.

The MongoDB connector lets your workflows interact with any MongoDB instance, including MongoDB Atlas, self-hosted clusters, and single-node deployments.

<Snippet file="connection-note.mdx" />

## Editor experience

Fields that take a MongoDB query, update, or aggregation pipeline (`filter`, `update`, `pipeline`, `command`, `documents`, `projection`, `sort`) render as a JSON editor; paste or type your queries directly without escaping.

Misspelled MongoDB operators are flagged inline with a suggestion. Typing `$grater_than` shows *Did you mean `$gt`?*. Aggregation variables (`$$ROOT`, `$$NOW`) and the positional update marker (`$`) are recognised and never flagged.

## Connection setup

You can connect using either a **connection string** (recommended for Atlas) or **individual credentials**.

<Steps>
  <Step title="Choose your connection method">
    **Option A: Connection String** (recommended for MongoDB Atlas):

    * Copy the connection string from your Atlas dashboard (e.g., `mongodb+srv://user:pass@cluster.mongodb.net/mydb`)

    **Option B: Individual credentials** (for self-hosted or direct connections):

    * **Host** (e.g., `localhost` or `mongo.example.com`)
    * **Port** (default: `27017`)
    * **Username** and **Password**
    * **Database** (optional, default database)
    * **Auth Source** (optional, authentication database, usually `admin`)
  </Step>

  <Step title="Add the connection in Spojit">
    Go to **Connections** in Spojit, click **Add Connection**, select **MongoDB**, and enter either:

    * **Connection String**: Your full MongoDB URI, or
    * **Host**, **Port**, **Username**, **Password**, **Database**, and **Auth Source** fields
  </Step>
</Steps>

<Tip>
  **MongoDB Atlas**: Copy the connection string from your cluster's **Connect** dialog. Make sure your IP is in the Atlas network access list.
</Tip>

### Common MongoDB settings

| Provider      | Connection method                       | Notes                         |
| ------------- | --------------------------------------- | ----------------------------- |
| MongoDB Atlas | Connection string (`mongodb+srv://...`) | Add IP to network access list |
| Self-hosted   | Host + credentials                      | Ensure auth is enabled        |

## Tools

<AccordionGroup>
  <Accordion title="run-command: Execute a raw database command">
    Execute any MongoDB database command such as `ping`, `dbStats`, `collStats`, `createUser`, etc.

    <ParamField body="command" type="object" required>
      MongoDB command object.
    </ParamField>

    <ParamField body="database" type="string">
      Database to run the command against. Defaults to the connection's database.
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "command": { "dbStats": 1 }
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "db": "myapp",
        "collections": 12,
        "objects": 45230,
        "dataSize": 15728640,
        "ok": 1
      }
    }
    ```
  </Accordion>

  <Accordion title="find-documents: Query documents from a collection">
    <ParamField body="collection" type="string" required>
      Collection name.
    </ParamField>

    <ParamField body="filter" type="object">
      MongoDB query filter (e.g., `{ "status": "active" }`).
    </ParamField>

    <ParamField body="projection" type="object">
      Fields to include (1) or exclude (0).
    </ParamField>

    <ParamField body="sort" type="object">
      Sort order (1 for ascending, -1 for descending).
    </ParamField>

    <ParamField body="limit" type="number">
      Maximum number of documents to return (default: 100).
    </ParamField>

    <ParamField body="skip" type="number">
      Number of documents to skip.
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "collection": "orders",
      "filter": { "status": "shipped" },
      "projection": { "orderId": 1, "total": 1, "customer": 1 },
      "sort": { "createdAt": -1 },
      "limit": 5
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "documents": [
          { "_id": "665a...", "orderId": "ORD-1234", "total": 99.99, "customer": "Alice" },
          { "_id": "665b...", "orderId": "ORD-1233", "total": 149.50, "customer": "Bob" }
        ],
        "count": 2
      }
    }
    ```
  </Accordion>

  <Accordion title="insert-documents: Insert documents into a collection">
    <ParamField body="collection" type="string" required>
      Collection name.
    </ParamField>

    <ParamField body="documents" type="object[]" required>
      Array of documents to insert.
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "collection": "users",
      "documents": [
        { "name": "Alice", "email": "alice@example.com", "role": "admin" },
        { "name": "Bob", "email": "bob@example.com", "role": "user" }
      ]
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "insertedCount": 2,
        "insertedIds": { "0": "665a...", "1": "665b..." }
      }
    }
    ```
  </Accordion>

  <Accordion title="update-documents: Update documents matching a filter">
    <ParamField body="collection" type="string" required>
      Collection name.
    </ParamField>

    <ParamField body="filter" type="object" required>
      Query filter to match documents.
    </ParamField>

    <ParamField body="update" type="object" required>
      Update operations using MongoDB operators (`$set`, `$inc`, `$push`, etc.).
    </ParamField>

    <ParamField body="upsert" type="boolean">
      Insert a new document if no match is found (default: false).
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "collection": "users",
      "filter": { "role": "user" },
      "update": { "$set": { "verified": true } }
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "matchedCount": 42,
        "modifiedCount": 42,
        "upsertedCount": 0,
        "upsertedId": null
      }
    }
    ```
  </Accordion>

  <Accordion title="delete-documents: Delete documents matching a filter">
    <ParamField body="collection" type="string" required>
      Collection name.
    </ParamField>

    <ParamField body="filter" type="object" required>
      Query filter to match documents to delete.
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "collection": "sessions",
      "filter": { "expiresAt": { "$lt": "2024-01-01T00:00:00Z" } }
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "deletedCount": 256
      }
    }
    ```
  </Accordion>

  <Accordion title="aggregate: Run an aggregation pipeline">
    <ParamField body="collection" type="string" required>
      Collection name.
    </ParamField>

    <ParamField body="pipeline" type="object[]" required>
      Aggregation pipeline stages (`$match`, `$group`, `$sort`, `$project`, `$lookup`, etc.).
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "collection": "orders",
      "pipeline": [
        { "$match": { "status": "completed" } },
        { "$group": { "_id": "$customer", "totalSpent": { "$sum": "$total" }, "orderCount": { "$sum": 1 } } },
        { "$sort": { "totalSpent": -1 } },
        { "$limit": 10 }
      ]
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "documents": [
          { "_id": "Alice", "totalSpent": 1250.00, "orderCount": 12 },
          { "_id": "Bob", "totalSpent": 980.50, "orderCount": 8 }
        ],
        "count": 2
      }
    }
    ```
  </Accordion>

  <Accordion title="list-databases: List all databases">
    List all databases accessible with the current credentials. No parameters required.

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "databases": [
          { "name": "admin", "sizeOnDisk": 40960 },
          { "name": "myapp", "sizeOnDisk": 15728640 },
          { "name": "analytics", "sizeOnDisk": 8388608 }
        ],
        "totalSize": 24158208
      }
    }
    ```
  </Accordion>

  <Accordion title="list-collections: List collections in a database">
    <ParamField body="database" type="string">
      Database name. Defaults to the connection's database.
    </ParamField>

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "collections": [
          { "name": "users", "type": "collection" },
          { "name": "orders", "type": "collection" },
          { "name": "system.views", "type": "collection" }
        ]
      }
    }
    ```
  </Accordion>

  <Accordion title="count-documents: Count documents in a collection">
    <ParamField body="collection" type="string" required>
      Collection name.
    </ParamField>

    <ParamField body="filter" type="object">
      Query filter. Counts all documents if omitted.
    </ParamField>

    **Example request:**

    ```json theme={null}
    {
      "collection": "users",
      "filter": { "status": "active" }
    }
    ```

    **Example response:**

    ```json theme={null}
    {
      "success": true,
      "data": {
        "count": 1542
      }
    }
    ```
  </Accordion>
</AccordionGroup>
