# MongoDB - Operation

> Execute CRUD operations and aggregation pipelines on MongoDB collections.

Source: https://docs.sommatic.ai/en/nodes/integrations.mongodb.operation/

- Slug: `integrations.mongodb.operation`
- Family: Integrations
- Version: 1.0.0
- Status: Available
- Execution: async

Execute CRUD operations and aggregation pipelines on MongoDB collections.

Connect your MongoDB instance and automate database operations — query documents, insert records, update fields, delete entries, and run aggregation pipelines.

**Operations:**
- **Find:** Query multiple documents with a filter.
- **Find One:** Retrieve a single document matching a filter.
- **Insert One / Insert Many:** Add one or multiple documents.
- **Update One / Update Many:** Modify documents matching a filter.
- **Delete One:** Remove a single document.
- **Aggregate:** Run an aggregation pipeline.

## Configuration

- `connection_id` (string, required): Connection credential for your MongoDB instance. Accepts credentials of type `connection-string` (mongodb:// URI) or `basic-auth` (username + password + host).
- `database` (string, optional, accepts expressions): Name of the MongoDB database. Required when the credential connection string does not embed a default database (common for Azure Cosmos DB for MongoDB, which omits the db name from the URI).
- `collection` (string, required, accepts expressions): Name of the MongoDB collection to operate on.
- `operation` (string, required): The database operation to perform. Allowed values: `find`, `findOne`, `insertOne`, `insertMany`, `updateOne`, `updateMany`, `deleteOne`, `aggregate`.
- `query` (object, optional, accepts expressions): MongoDB filter document or aggregation pipeline array. Shown when: operation = `find` | `findOne` | `updateOne` | `updateMany` | `deleteOne` | `aggregate`.
- `update` (object, optional, accepts expressions): Update operators object or document(s) to insert. Shown when: operation = `insertOne` | `insertMany` | `updateOne` | `updateMany`.

## Output ports

- `out` (default): Operation result
- `empty`: When find/findOne returns no documents
- `error`: Error occurred during execution

## Input contract

- `connection_id` (string, required)
- `database` (string, optional)
- `collection` (string, required)
- `operation` (string, required)
- `query` (object, optional)
- `update` (object, optional)

## Output contract

- `result` (object, optional): Result document(s) or operation status

## In expressions

What a later node can read from this node's output with `$("MongoDB - Operation").item.json.<path>` (write your node's label instead of `MongoDB - Operation`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `out`, from the output shown in Ports.

- `$("MongoDB - Operation").item.json.result` (object) = `[…] (1)`: Result document(s) or operation status


## How it works

Runs one MongoDB operation (find, findOne, insertOne, insertMany, updateOne, updateMany, deleteOne, deleteMany or aggregate) on a collection and returns the driver result under `result`. Connection failures are retried; the operation itself runs once.

1. Resolves the expressions of the node config. Empty `connection_id`, `database`, `collection` and `operation` fall back to the incoming item. The filter is taken from `query`, then `filter`, then the incoming item's `query` or `filter`; the document from `update`, then `document`, then the incoming item. Empty objects `{}` count as missing.
2. Resolves the connection: a `mongodb://` URI in `connection_id`, a `connection-string` credential, or a `basic-auth` / `object` credential with `username`, `password`, `host`, `port` (default 27017), optional `dbName` and `options`. The database is `database`, else the URI path, else the credential's `dbName`.
3. Connects with 10-second server-selection and connect timeouts, retrying only the connection on transient network errors (ECONNREFUSED, ETIMEDOUT, MongoServerSelectionError, MongoNetworkError…).
4. Parses string filters and documents as JSON, then runs the operation. updateOne / updateMany always send `{ $set: <document> }`; aggregate uses the filter as the pipeline when it is an array.
5. Closes the client and returns `{ result: [] }` on `empty` when the result is `null` or an empty array, otherwise `{ result }` on `out`.

## In a workflow

### Node

```json
{
  "node_id": "node-find-orders",
  "label": "Find open orders",
  "operator_slug": "integrations.mongodb.operation",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "database": "sales",
    "collection": "orders",
    "operation": "find",
    "query": {
      "status": "open",
      "customer_id": "{{ $json.customer_id }}"
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": [
      {
        "_id": "6745f2b3c1a9e43d2f0a1b7c",
        "order_id": "ord_123",
        "status": "open"
      }
    ]
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `out`

The operation returned data: documents for find / findOne / aggregate, or the driver's write result (`acknowledged`, `insertedId`, `matchedCount`, `modifiedCount`, `deletedCount`…) for writes. A write that matched nothing still leaves here.

```json
{
  "result": [
    {
      "_id": "6745f2b3c1a9e43d2f0a1b7c",
      "order_id": "ord_123",
      "status": "open"
    }
  ]
}
```

### `empty`

find or aggregate returned no documents, or findOne found nothing.

```json
{
  "result": []
}
```

### `error`

Validation, credential resolution, the connection (after retries) or the operation failed.

```json
{
  "error": "Server selection timed out after 10000 ms"
}
```

## Behaviour in the code

- `update`: For updateOne / updateMany it is always wrapped in `$set`, so update operators such as `$inc` or `$push` are not supported: pass the fields to set. For insertOne / insertMany it is the document (insertMany wraps a single object in an array).
- `query`: A string is parsed as JSON; invalid JSON silently becomes `{}`, which matches every document. Check the filter before running updateMany or deleteMany. For aggregate it must be an array; an object runs an empty pipeline.
- `operation`: Besides the listed values, the code accepts `deleteMany` and the aliases `insert` (insertOne), `update` (updateMany) and `delete` (deleteMany).
- `filter`: Undeclared alias of `query`; `document` is the undeclared alias of `update`.
- `execution`: Not declared in this node's schema, but read for the connection retries: `retryOnFail: false` means one attempt; otherwise `maxTries` (default 3), with `waitBetweenTries` as the base backoff. The undeclared `http_retry_max_attempts` (clamped to 1–5), `http_retry_backoff_ms` (default 1000, doubled per attempt plus up to 250 ms jitter) and `http_retry_max_wait_ms` (default 20000, at most 30000) override them.
- `mongo_server_selection_timeout_ms`: Undeclared. Server-selection timeout in ms (default 10000). `mongo_connect_timeout_ms` sets the connect timeout the same way. Neither limits the operation itself.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `connection_id is required` | `error` | No credential in the config or in the incoming item. `collection is required` and `operation is required` work the same way. |
| `Could not resolve database name for <connection_id>. Set the 'database' config field explicitly (required for Azure Cosmos DB for MongoDB and any other connection string that does not embed a default database).` | `error` | Neither `database`, the URI path nor the credential provide a database name. |
| `Unknown operation: <operation>` | `error` | `operation` is not one of the supported names or aliases. |
| `Credential <connection_id> has unsupported type '<type>' for integrations.mongodb.operation. Use 'connection-string' or 'basic-auth'.` | `error` | The credential type is not supported by this node. |
| `Server selection timed out after <ms> ms` | `error` | The server could not be reached within the timeout on every attempt. |

## Notes and limits

- Only the connection phase is retried, so a write is never applied twice.
- find and aggregate return every matching document; there is no limit, projection or sort option. Use an aggregate pipeline with `$match`, `$project`, `$sort` and `$limit` to bound the result.
- A new client is opened and closed on every run.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "integrations.mongodb.operation",
  "name": "MongoDB - Operation",
  "category": "integrations",
  "version": "1.0.0",
  "description": "Execute CRUD operations and aggregation pipelines on MongoDB collections.\n\n  Connect your MongoDB instance and automate database operations — query documents, insert records, update fields, delete entries, and run aggregation pipelines.\n\n  **Operations:**\n  - **Find:** Query multiple documents with a filter.\n  - **Find One:** Retrieve a single document matching a filter.\n  - **Insert One / Insert Many:** Add one or multiple documents.\n  - **Update One / Update Many:** Modify documents matching a filter.\n  - **Delete One:** Remove a single document.\n  - **Aggregate:** Run an aggregation pipeline.",
  "capabilities": [
    "nosql",
    "database",
    "mongo",
    "mongodb"
  ],
  "group": [
    {
      "key": "mongodb",
      "name": "MongoDB",
      "icon_url": "/icons/integrations/mongodb/mongodb.svg"
    }
  ],
  "icon_url": "/icons/integrations/mongodb/mongodb.svg",
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "MongoDB Credential",
        "description": "Connection credential for your MongoDB instance. Accepts credentials of type `connection-string` (mongodb:// URI) or `basic-auth` (username + password + host).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "connection-string",
            "basic-auth"
          ],
          "types": [
            "mongo"
          ]
        }
      },
      "database": {
        "type": "string",
        "title": "Database",
        "description": "Name of the MongoDB database. Required when the credential connection string does not embed a default database (common for Azure Cosmos DB for MongoDB, which omits the db name from the URI).",
        "format": "expression"
      },
      "collection": {
        "type": "string",
        "title": "Collection",
        "description": "Name of the MongoDB collection to operate on.",
        "format": "expression"
      },
      "operation": {
        "type": "string",
        "title": "Operation",
        "description": "The database operation to perform.",
        "enum": [
          "find",
          "findOne",
          "insertOne",
          "insertMany",
          "updateOne",
          "updateMany",
          "deleteOne",
          "aggregate"
        ]
      },
      "query": {
        "type": "object",
        "title": "Filter / Query",
        "description": "MongoDB filter document or aggregation pipeline array.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "find",
              "findOne",
              "updateOne",
              "updateMany",
              "deleteOne",
              "aggregate"
            ]
          }
        }
      },
      "update": {
        "type": "object",
        "title": "Update / Document",
        "description": "Update operators object or document(s) to insert.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "insertOne",
              "insertMany",
              "updateOne",
              "updateMany"
            ]
          }
        }
      }
    },
    "required": [
      "connection_id",
      "collection",
      "operation"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "database": {
        "type": "string"
      },
      "collection": {
        "type": "string"
      },
      "operation": {
        "type": "string"
      },
      "query": {
        "type": "object"
      },
      "update": {
        "type": "object"
      }
    },
    "required": [
      "connection_id",
      "collection",
      "operation"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "object",
        "description": "Result document(s) or operation status"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "description": "Operation result",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Not Found",
      "description": "When find/findOne returns no documents",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Error occurred during execution",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "db-io"
  ],
  "tags": [
    "nosql",
    "database"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "MongoDB Credential",
      "description": "Connection credential for your MongoDB instance. Accepts credentials of type `connection-string` (mongodb:// URI) or `basic-auth` (username + password + host).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "connection-string",
          "basic-auth"
        ],
        "types": [
          "mongo"
        ]
      }
    },
    "database": {
      "type": "string",
      "title": "Database",
      "description": "Name of the MongoDB database. Required when the credential connection string does not embed a default database (common for Azure Cosmos DB for MongoDB, which omits the db name from the URI).",
      "format": "expression"
    },
    "collection": {
      "type": "string",
      "title": "Collection",
      "description": "Name of the MongoDB collection to operate on.",
      "format": "expression"
    },
    "operation": {
      "type": "string",
      "title": "Operation",
      "description": "The database operation to perform.",
      "enum": [
        "find",
        "findOne",
        "insertOne",
        "insertMany",
        "updateOne",
        "updateMany",
        "deleteOne",
        "aggregate"
      ]
    },
    "query": {
      "type": "object",
      "title": "Filter / Query",
      "description": "MongoDB filter document or aggregation pipeline array.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "find",
            "findOne",
            "updateOne",
            "updateMany",
            "deleteOne",
            "aggregate"
          ]
        }
      }
    },
    "update": {
      "type": "object",
      "title": "Update / Document",
      "description": "Update operators object or document(s) to insert.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "insertOne",
            "insertMany",
            "updateOne",
            "updateMany"
          ]
        }
      }
    }
  },
  "required": [
    "connection_id",
    "collection",
    "operation"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "database": {
      "type": "string"
    },
    "collection": {
      "type": "string"
    },
    "operation": {
      "type": "string"
    },
    "query": {
      "type": "object"
    },
    "update": {
      "type": "object"
    }
  },
  "required": [
    "connection_id",
    "collection",
    "operation"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "object",
      "description": "Result document(s) or operation status"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Result",
    "description": "Operation result",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Not Found",
    "description": "When find/findOne returns no documents",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Error occurred during execution",
    "is_default": false,
    "supports_condition": false
  }
]
```
