> For the complete documentation index, see [llms.txt](https://docs.soapjs.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.soapjs.com/plugins/node.js/soap-mongodb.md).

# Soap MongoDB

`@soapjs/soap-node-mongo` is the MongoDB integration: a `Source` implementation (`MongoSource`), a query factory, and connection management.

> Current version: **0.7.x**. Peer deps: `@soapjs/soap` ≥ 0.10, `mongodb`.

### Install

```bash
npm install @soapjs/soap-node-mongo mongodb
```

### Connect

```typescript
import { SoapMongo, MongoConfig, MongoSource } from '@soapjs/soap-node-mongo';

const config = new MongoConfig('mydb', ['localhost'], ['27017'], user, password);
const soapMongo = await SoapMongo.create(config);
```

### Source

`MongoSource` implements the full `Source` contract and is wrapped in a `DatabaseContext` for a repository:

```typescript
import { DatabaseContext } from '@soapjs/soap';

const source = new MongoSource(soapMongo, 'characters');
const context = new DatabaseContext(source, new CharacterMapper(), soapMongo.sessions);
```

Methods: `find` · `count` · `aggregate` · `insert` · `update` · `remove` · `native`.

### Queries

* **`find` / `count`** take `FindParams` / `CountParams` built with `Where`; the query factory translates `Where` into a MongoDB filter — no Mongo syntax in your repo.
* **`aggregate`** runs a portable `AggregationParams` (`groupBy`, `sum`, `where`, …).

### Native queries

For pipelines, commands, or operators the abstraction can't express, use `native()` with a `RepositoryQuery` whose `build()` returns the raw payload:

| `build()` returns                    | Runs as              |
| ------------------------------------ | -------------------- |
| an array                             | aggregation pipeline |
| `{ kind: 'find', filter, options? }` | `collection.find`    |
| `{ kind: 'command', command }`       | `db.command`         |

See Using Native Queries.

### Read/write split

Set `readPreference` in the connection pool config and use a separate `MongoSource` per connection (read replica vs primary). See the [demo](https://github.com/soapjs/soap-node-demo).
