---
title: 与 MongoDB 一起使用
---

来源：https://mikro-orm.io/docs/usage-with-mongo

要把 MikroORM 与 mongo 数据库一起使用，别忘了安装 `@mikro-orm/mongodb` 依赖。然后在应用启动过程中调用 `MikroORM.init()`：

> 要访问 `em.aggregate()` 这类驱动专属方法，你需要在调用 `MikroORM.init<D>()` 时指定驱动类型。或者也可以把 `orm.em` 断言为驱动包导出的 `EntityManager`：
>
> ```ts
> import { EntityManager } from '@mikro-orm/mongodb';
> const em = orm.em as EntityManager;
> const qb = em.aggregate(...);
> ```

> 你需要使用 `clientUrl` 来设置主机，不支持使用 `host` 或 `port`。

```ts
import { MikroORM } from '@mikro-orm/mongodb'; // 或其他任意驱动包

const orm = await MikroORM.init({
  entities: [Author, Book, ...],
  dbName: 'my-db-name',
  clientUrl: '...',
});
console.log(orm.em); // 通过 `em` 属性访问 EntityManager
```

<a id="defining-entity"></a>
## 定义实体

定义实体时，别忘了像这样定义主键：

```ts
@PrimaryKey()
_id: ObjectId;

@SerializedPrimaryKey()
id!: string; // 不会保存到数据库
```

> 只有 `_id: ObjectId` 会被保存到数据库。`id: string` 是虚拟的，同时也是可选的。

<a id="objectid-and-string-id-duality"></a>
## ObjectId 与字符串 id 的二元性

每个实体同时具有 `ObjectId` 与 `string` 两种 id，`EntityManager` 与 `EntityRepository` 的所有方法也支持用这两种 id 进行查询。

```ts
const author = orm.em.getReference('...id...');
console.log(author.id);  // 返回 '...id...'
console.log(author._id); // 返回 ObjectId('...id...')

// 以下写法都会返回相同的结果
const article = '...article id...'; // 字符串 id
const book = '...book id...'; // 字符串 id
const repo = orm.em.getRepository(Author);
const foo1 = await repo.find({ id: { $in: [article] }, favouriteBook: book });
const bar1 = await repo.find({ id: { $in: [new ObjectId(article)] }, favouriteBook: new ObjectId(book) });
const foo2 = await repo.find({ _id: { $in: [article] }, favouriteBook: book });
const bar2 = await repo.find({ _id: { $in: [new ObjectId(article)] }, favouriteBook: new ObjectId(book) });
```

<a id="manytomany-collections-with-inlined-pivot-array"></a>
## 带内联中间数组的 ManyToMany 集合

与使用中间表的 SQL 驱动不同，在 mongo 中我们可以利用已有的数组类型来存储集合项（标识符）的数组。这种方式有两个主要好处：

1. 集合保存在拥有方实体上，因此即便还没初始化集合，你也知道里面有多少项。
2. 由于没有中间表，最终的数据库查询要简单得多。

<a id="transactions"></a>
## 事务

MongoDB 驱动支持事务。要使用事务，你需要遵守几点：

- 需要使用副本集（参见 [run-rs](https://github.com/vkarpov15/run-rs)）
- 隐式事务默认是禁用的
  - 使用 `implicitTransactions: true` 可全局启用
  - 或通过 `em.transactional()` 使用显式的事务界定
- 在使用集合之前，你需要显式创建所有集合
  - 用 `orm.schema.create()` 方法来做到这一点

```sh
# 先创建副本集
$ run-rs -v 4.2.3
```

```ts
// 务必从 MongoDriver 包导入
import { MikroORM } from '@mikro-orm/mongodb';

const orm = await MikroORM.init({
  entities: [Author, Book, ...],
  clientUrl: 'mongodb://localhost:27017,localhost:27018,localhost:27019/my-db-name?replicaSet=rs0',
  implicitTransactions: true, // 默认为 false
});

await orm.schema.create();
```

<a id="indexes"></a>
## 索引

MongoDB 驱动支持索引与唯一约束。你可以按[定义实体章节](./18-defining-entities.md#indexes)所述使用 `@Index()` 与 `@Unique()`。要在初始化 ORM 时自动创建新索引，你需要启用 `ensureIndexes` 选项。

```ts
const orm = await MikroORM.init({
  entities: [Author, Book, ...],
  dbName: 'my-db-name',
  ensureIndexes: true, // 默认为 false
});
```

或者，你也可以在 `SchemaGenerator` 上调用 `ensureIndexes()` 方法：

> MongoDB 同样支持 SchemaGenerator。

```ts
await orm.schema.ensureIndexes();
```

你可以通过 `options` 参数传入额外的索引/唯一约束选项：

```ts
@Unique({ options: { partialFilterExpression: { name: { $exists: true } } }})
```

你也可以通过传入 `type` 参数创建文本索引：

```ts
@Index({ properties: ['name', 'caption'], type: 'text' })
```

如果在索引定义中只提供了 `options`，它会被原样使用，这让你可以定义任意类型的索引：

```ts
@Index({ options: { point: '2dsphere', title: -1 } })
```

要设置索引权重，可以向 `options` 参数传入一个元组：

```ts
@Index({ options: [
  { title: 'text', perex: 'text', key: 1 },
  { weights: { title: 10, perex: 5 } },
] })
```

<a id="native-collection-methods"></a>
## 原生集合方法

有时你需要执行某些批量操作，或者只是想用初始测试数据填充数据库。为这类操作使用 ORM 会带来不必要的样板代码。这种情况下，你可以使用 `insert/nativeUpdate/nativeDelete` 方法之一：

```ts
em.insert<T extends AnyEntity>(entityName: string, data: any): Promise<IPrimaryKey>;
em.nativeUpdate<T extends AnyEntity>(entityName: string, where: FilterQuery<T>, data: any): Promise<number>;
em.nativeDelete<T extends AnyEntity>(entityName: string, where: FilterQuery<T> | any): Promise<number>;
```

这些方法分别执行原生驱动方法，例如 Mongo 的 `insertOne/updateMany/deleteMany` 集合方法。这是所有驱动通用的接口，因此对 MySQL 驱动而言，它会发出原生 SQL 查询。请记住，它们不会把结果水合成实体，也不会触发生命周期钩子。

它们也可以作为 `EntityRepository` 的快捷方式使用：

```ts
EntityRepository.insert(data: any): Promise<IPrimaryKey>;
EntityRepository.nativeUpdate(where: FilterQuery<T>, data: any): Promise<number>;
EntityRepository.nativeDelete(where: FilterQuery<T> | any): Promise<number>;
```

调用 `aggregate` 方法也有快捷方式：

```ts
em.aggregate(entityName: string, pipeline: any[]): Promise<any[]>;
EntityRepository.aggregate(pipeline: any[]): Promise<any[]>;
```

<a id="query-options"></a>
## 查询选项

你可以向 `em.find()` 与 `em.count()` 传入 MongoDB 专属的查询选项：

<a id="collation"></a>
### 排序规则（Collation）

控制过滤与排序时的字符串比较规则。传入一个 `CollationOptions` 对象——在 MongoDB 中，排序规则会作用于整个查询操作，同时影响 `WHERE` 条件与 `ORDER BY`：

```ts
// 查找与排序均不区分大小写
const users = await em.find(User, { name: 'john' }, {
  collation: { locale: 'en', strength: 2 },
  orderBy: { name: QueryOrder.ASC },
});
```

<a id="index-hints"></a>
### 索引提示

向原生的 `hint` 选项传入一个字符串（索引名）或对象（索引规格）：

```ts
const users = await em.find(User, {}, {
  indexHint: 'name_1',
});

// 或使用索引规格
const users = await em.find(User, {}, {
  indexHint: { name: 1 },
});
```

<a id="maxtimems-and-allowdiskuse"></a>
### `maxTimeMS` 与 `allowDiskUse`

```ts
const users = await em.find(User, {}, {
  maxTimeMS: 5000,     // 查询超时时间（毫秒）
  allowDiskUse: true,  // 允许大型排序使用磁盘
});
```

> `collation`、`indexHint` 与 `maxTimeMS` 选项同样适用于 `em.count()`。`allowDiskUse` 选项仅适用于 `em.find()`。
