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

# MongoDB Connector

> Store MQTT data in MongoDB as documents and read it back with find events

## MongoDB Overview

The `MONGODB` connector inserts MQTT messages into MongoDB collections as documents and reads them back. Each event either inserts one document or runs a find, and models can store into a collection with `STORE IN`.

> [!NOTE]
>
> MongoDB suits IoT data whose shape changes over time. Store sensor readings, events, and logs without defining a table first.

## Basic Syntax

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE MONGODB
    ADD MONGODB_CONFIG
        WITH CONNECTION_STRING GET SECRET "MONGO_URI"
        WITH DATABASE "iot"
    ADD EVENT StoreSensorReading
        WITH SOURCE_TOPIC "sensors/+/reading"
        WITH QUERY "CLEAN:{collection: readings, document: {sensor_id: {topic.2}, value: {payload.json.value}}}"
```

***

## Connection Configuration

### MONGODB\_CONFIG Parameters

**CONNECTION\_STRING** `string` *required*

MongoDB URI: `mongodb://host:port/?options` or `mongodb+srv://host/?options`. Replica sets, TLS, timeouts, and pool size are set here as URI options. The URI is checked at deploy: one that cannot be read is refused, and the error never repeats the URI.

**DATABASE** `string` *required*

Database that the events and `STORE IN` use.

> [accordion] Optional Settings
>
> **USERNAME** `string`
>
> Login given apart from the URI, so the password needs no percent-encoding. It takes precedence over a login in the URI. It authenticates exactly as a login in the URI would, so `authSource`, `authMechanism`, and `authMechanismProperties` from the URI still apply.
>
> **PASSWORD** `string`
>
> Password for `USERNAME`. Use `GET SECRET`.

> [!WARNING]
>
> **Never hardcode credentials in production.** Keep the URI or the password in an encrypted secret:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> WITH CONNECTION_STRING GET SECRET "MONGO_URI"
> ```
>
> See [Environment Variables & Secrets](https://docs.coreflux.org/latest/mqtt-broker/secrets-and-env.md) for setup and usage.

### Credentials in the URI

A user name or password inside the URI must be percent-encoded: `@ : / ? # [ ] %` become `%40 %3A %2F %3F %23 %5B %5D %25`. A URI with an unencoded `@` in the password is refused at deploy. To avoid encoding, leave the login out of the URI:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE MONGODB
    ADD MONGODB_CONFIG
        WITH CONNECTION_STRING "mongodb://mongodb.example.com:27017/?authSource=admin"
        WITH DATABASE "iot"
        WITH USERNAME "iot_writer"
        WITH PASSWORD GET SECRET "MONGO_PASSWORD"
```

### URI options and defaults

The connector applies these defaults only when the URI does not set the option itself:

| URI option | Connector default |
| - | - |
| `connectTimeoutMS` | 5000 |
| `serverSelectionTimeoutMS` | 5000 |
| `socketTimeoutMS` | 10000 (a find or insert that runs longer fails) |
| `maxPoolSize` | 10 |

Every other option, such as `retryWrites`, `replicaSet`, or `tls`, is used as written in the URI.

### TLS

Set TLS in the URI with `tls=true`. Add `tlsCAFile=/path/ca.pem` for a private certificate authority. `tlsInsecure=true` skips certificate checks; use it only in a test setup with a self-signed certificate.

***

## Event Configuration

### EVENT Parameters

**SOURCE\_TOPIC** `string`

MQTT topic pattern that triggers the event. Supports wildcards. Use `SOURCE_TOPIC` or `EVERY`.

**QUERY** `string` *required*

An insert or a find, as a CLEAN or JSON object. See [Query format](#query-format).

> [accordion] Optional Settings
>
> **DESTINATION\_TOPIC** `string`
>
> MQTT topic where the result is published. A `+` in it takes the matching level of the source topic. Required for an `EVERY` event.
>
> **EVERY** `string`
>
> Run the event on a schedule, for example `WITH EVERY 10 SECONDS`.

***

## Query format

`QUERY` is a JSON object, or the CLEAN form (`CLEAN:{key: value}` with unquoted keys and values). CLEAN is the practical form inside a LoT string. Extended JSON such as `{"$oid": "…"}` and `{"$date": "…"}` works in filters and documents.

A query with a `document` key inserts. Any other query is a find.

| Operation | Keys |
| - | - |
| Insert one document | `collection` (required), `document` (a JSON object). A `timestamp` date (UTC) is added unless the document has one. |
| Find | `collection` (required), `filter`, `projection`, `sort`, `skip`, `limit`. Any other key is refused, so a typo such as `filters` fails instead of returning every document. |

Update, delete, and aggregation are not supported.

### Find options

| Key | Example | Meaning |
| - | - | - |
| `filter` | `{line: A}` · `{value: {$gt: 10}}` | A JSON object, with MongoDB query operators. Omit it to match every document. |
| `projection` | `{sensor_id: 1, value: 1}` · `"sensor_id, value"` | Fields to return. |
| `sort` | `{timestamp: -1}` · `"timestamp desc"` | Sort order. |
| `skip` | `20` | Documents to skip. |
| `limit` | `10` | Most documents to return. `0` or no `limit` returns all matches. |

### Placeholders

| Placeholder | Description |
| - | - |
| `{payload}` | The whole payload |
| `{value.json}` | The whole JSON payload |
| `{payload.json.key}` / `{value.json.key}` | A field of the JSON payload |
| `{topic.N}` | Level `N` of the source topic (1-based) |
| `{source_topic}` | The source topic |
| `{timestamp}` | The current time as ISO 8601 text (UTC) |
| `{env.NAME}` / `{secret.NAME}` | An environment variable or a secret |

Each placeholder goes in as one JSON value, so payload text is stored as sent:

* A JSON number, `true`, `false`, or `null` keeps its type. Text that reads as a number or as `true` / `false` is stored as one.
* Any other text is stored as a string, with its quotes, apostrophes, commas, semicolons, and braces. Dates keep their offset.
* `{value.json}`, or a `{payload.json.key}` that holds an object or an array, goes in as that JSON.
* Inside a quoted string (`"note: {payload}"`), the value is part of that string.

> [!WARNING]
>
> A payload value that is a JSON object goes into a `filter` as an object, so it can carry query operators such as `{"$ne": null}`. Do not build a find filter from payloads you do not trust. Keep untrusted publishers off the event's source topic with a [rule](https://docs.coreflux.org/latest/lot-language/rules/overview).

***

## Writing Data

> [tab] Basic Document Storage
>
> Store each JSON payload with its topic:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR SensorStorage WITH TYPE MONGODB
>     ADD MONGODB_CONFIG
>         WITH CONNECTION_STRING GET SECRET "MONGO_URI"
>         WITH DATABASE "iot"
>     ADD EVENT StoreReading
>         WITH SOURCE_TOPIC "sensors/+/reading"
>         WITH DESTINATION_TOPIC "db/mongo/status"
>         WITH QUERY "CLEAN:{collection: readings, document: {topic: {source_topic}, data: {value.json}}}"
> ```
>
> Each insert publishes a result to `DESTINATION_TOPIC`:
>
> ```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> {"success": true, "collection": "readings", "insertedId": "674f1c2e9b1d4a0012ab34cd", "timestamp": "2026-11-26T10:30:00.123Z"}
> ```

> [tab] Structured Documents
>
> Build a document from fields of the payload and the topic:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR StructuredStorage WITH TYPE MONGODB
>     ADD MONGODB_CONFIG
>         WITH CONNECTION_STRING GET SECRET "MONGO_URI"
>         WITH DATABASE "iot"
>     ADD EVENT StoreSensor
>         WITH SOURCE_TOPIC "sensors/+/data"
>         WITH QUERY "CLEAN:{collection: sensor_data, document: {sensor_id: {topic.2}, temperature: {payload.json.temperature}, humidity: {payload.json.humidity}}}"
> ```
>
> **Input at** `sensors/temp001/data`:
>
> ```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> {"temperature": 23.5, "humidity": 65}
> ```
>
> **Stored document:**
>
> ```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> {
>   "_id": {"$oid": "674f1c2e9b1d4a0012ab34cd"},
>   "sensor_id": "temp001",
>   "temperature": 23.5,
>   "humidity": 65,
>   "timestamp": {"$date": "2026-11-26T10:30:00.123Z"}
> }
> ```

> [tab] Multiple Collections
>
> Send different topics to different collections:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR MultiCollection WITH TYPE MONGODB
>     ADD MONGODB_CONFIG
>         WITH CONNECTION_STRING GET SECRET "MONGO_URI"
>         WITH DATABASE "iot"
>
>     ADD EVENT StoreSensors
>         WITH SOURCE_TOPIC "sensors/#"
>         WITH QUERY "CLEAN:{collection: sensors, document: {topic: {source_topic}, data: {value.json}}}"
>
>     ADD EVENT StoreAlerts
>         WITH SOURCE_TOPIC "alerts/#"
>         WITH QUERY "CLEAN:{collection: alerts, document: {topic: {source_topic}, alert: {value.json}}}"
> ```

> [tab] Replica Set
>
> Connect to a replica set with the URI:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR ReplicaSetStorage WITH TYPE MONGODB
>     ADD MONGODB_CONFIG
>         WITH CONNECTION_STRING "mongodb://mongo1.example.com:27017,mongo2.example.com:27017,mongo3.example.com:27017/?replicaSet=rs0&authSource=admin"
>         WITH DATABASE "iot"
>         WITH USERNAME "iot_writer"
>         WITH PASSWORD GET SECRET "MONGO_PASSWORD"
>     ADD EVENT StoreData
>         WITH SOURCE_TOPIC "data/#"
>         WITH QUERY "CLEAN:{collection: data, document: {topic: {source_topic}, payload: {value.json}}}"
> ```

> [!NOTE]
>
> **Alternative: STORE IN with Models.** Instead of writing an insert query, bind a [model](https://docs.coreflux.org/latest/lot-language/models/overview) to this connector. Each `PUBLISH MODEL` inserts one document with the model's fields and their JSON types, plus a `timestamp` date unless the model has a `timestamp` field. MongoDB creates the collection on first use:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE MODEL SensorReading
>     ADD STRING "sensor_id"
>     ADD DOUBLE "value"
>     STORE IN "SensorStorage"
>         WITH TABLE "readings"
> ```
>
> See [Data Storage Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview#step-2-store-data) for the full STORE IN workflow.

***

## Reading Data

A find event reads documents on demand. Publish to its `SOURCE_TOPIC`, and the matching documents are published to `DESTINATION_TOPIC` as one JSON array:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE MONGODB
    ADD MONGODB_CONFIG
        WITH CONNECTION_STRING GET SECRET "MONGO_URI"
        WITH DATABASE "iot"
    ADD EVENT GetLatestReadings
        WITH SOURCE_TOPIC "db/query/latest"
        WITH DESTINATION_TOPIC "db/result/latest"
        WITH QUERY "CLEAN:{collection: readings, filter: {sensor_id: {payload}}, sort: {timestamp: -1}, limit: 10}"
```

To run it, publish the sensor ID to the source topic:

```
Topic:   db/query/latest
Payload: temp001
```

The result is relaxed Extended JSON. Numbers and text appear as they are, `_id` as `{"$oid": "…"}`, dates as `{"$date": "…"}`, and decimals as `{"$numberDecimal": "…"}`:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
[{"_id": {"$oid": "674f1c2e9b1d4a0012ab34cd"}, "sensor_id": "temp001", "value": 23.5, "timestamp": {"$date": "2026-11-26T10:30:00.123Z"}}]
```

### Timed Polling

An `EVERY` event runs the same find on a schedule:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
    ADD EVENT PollHighReadings
        WITH EVERY 10 SECONDS
        WITH DESTINATION_TOPIC "reports/readings/high"
        WITH QUERY "CLEAN:{collection: readings, filter: {value: {$gt: 30}}, projection: {sensor_id: 1, value: 1}, sort: {timestamp: -1}, limit: 50}"
```

### When an event fails

A failed insert or find publishes nothing. The error is logged, and the event's `ON ERROR` block runs. A query the server refuses leaves the connector connected. Only a connection failure marks it disconnected.

***

## While MongoDB is unreachable

After a connection failure, the next event or `STORE IN` checks MongoDB at once. If MongoDB answers, the work runs. If not, the work is skipped and later checks run at most every 5 seconds. Work that arrives between checks is skipped instead of waiting out the server-selection timeout.

Each check logs how many events and `STORE IN` documents were skipped: a warning while MongoDB is still down, and an information line with the total when the connector reconnects.

A removed or redeployed connector closes its connections. Another connector with the same URI keeps working.

***

## Checking the connection

`-checkConnectorConnection <Name>` pings the database. The reply names the database and the hosts and ports it tried, never the login or the password. The check waits at most 10 seconds.

```
Topic:   $SYS/Coreflux/Command
Payload: -checkConnectorConnection SensorDB
```

A failed check says what to look at: authentication, TLS, a refused connection, an unknown host, or no answer within the server-selection timeout.

***

## Connection String Examples

| Scenario | Connection String |
| - | - |
| Local | `mongodb://localhost:27017` |
| Authenticated | `mongodb://user:password@mongodb.example.com:27017/?authSource=admin` |
| Replica Set | `mongodb://host1:27017,host2:27017/?replicaSet=rs0` |
| TLS | `mongodb://mongodb.example.com:27017/?tls=true&tlsCAFile=/certs/ca.pem` |
| Atlas | `mongodb+srv://user:password@cluster0.example.mongodb.net/` |

***

## Troubleshooting

> [accordion] Deploy refused: CONNECTION\_STRING is not a valid MongoDB URI
>
> * Start the URI with `mongodb://` or `mongodb+srv://`
> * Percent-encode `@ : / ? # [ ] %` in the user name and password, or move the login to `USERNAME` and `PASSWORD`

> [accordion] Connection refused or no answer
>
> * Check that MongoDB is running and listening on that host and port
> * Check that a firewall allows the connection (port 27017 by default)
> * For Atlas, add the broker's address to the IP access list

> [accordion] Authentication failed
>
> * Check the user name and password
> * Check that `authSource` names the authentication database
> * Check that the user has rights on the target database

> [accordion] Event fails or a find returns nothing
>
> * Name the `collection` in every query
> * Use only `collection`, `filter`, `projection`, `sort`, `skip`, and `limit` in a find
> * Write `filter`, and the object forms of `projection` and `sort`, as JSON objects
> * Add a `DESTINATION_TOPIC` to see the result

***

## Next Steps

> [card] [Data Storage Connectors Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview)
>
> Compare all storage options.

> [card] [OpenSearch Connector](https://docs.coreflux.org/latest/connectors/data-storage/opensearch.md)
>
> Configure OpenSearch for search and analytics.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.