# MongoDB

> 英文标题：MongoDB
> 官网原文：https://typeorm.io/docs/drivers/mongodb
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 166 块

---

<!-- EN -->
# MongoDB

<!-- ZH -->
# MongoDB

<!-- EN -->
## MongoDB support

<!-- ZH -->
## MongoDB 支持

<!-- EN -->
TypeORM has basic MongoDB support (Node.js driver **v7 or later**).

<!-- ZH -->
TypeORM 提供了基础的 MongoDB 支持（Node.js 驱动 **v7 或更高版本**）。

<!-- EN -->
Most of TypeORM functionality is RDBMS-specific, this page contains all MongoDB-specific functionality.

<!-- ZH -->
TypeORM 的大部分功能都是 RDBMS 专属的，本页包含所有 MongoDB 专属功能。

<!-- EN -->
## Installation

<!-- ZH -->
## 安装

<!-- EN -->
```shell
npm install mongodb
```

<!-- ZH -->
```shell
npm install mongodb
```

<!-- EN -->
## Data Source Options

<!-- ZH -->
## 数据源选项

<!-- EN -->
* `appName` - The name of the application that created this MongoClient instance. MongoDB will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections.

<!-- ZH -->
* `appName` - 创建该 MongoClient 实例的应用名称。MongoDB 会在每次建立连接时把这个值打印到服务器日志中。它也会被记录在慢查询日志和 profile 集合中。

<!-- EN -->
* `authMechanism` - Sets the authentication mechanism that MongoDB will use to authenticate the connection.

<!-- ZH -->
* `authMechanism` - 设置 MongoDB 用于认证该连接的认证机制。

<!-- EN -->
* `authSource` - Specify the database name associated with the user's credentials.

<!-- ZH -->
* `authSource` - 指定与用户凭据关联的数据库名。

<!-- EN -->
* `autoEncryption` - Optionally enable in-use auto encryption.

<!-- ZH -->
* `checkServerIdentity` - 验证证书 `cert` 是否签发给 `hostname`。

<!-- EN -->
* `checkServerIdentity` - Verifies the certificate `cert` is issued to `hostname`.

<!-- ZH -->
* `autoEncryption` - 可选地启用使用中自动加密。

<!-- EN -->
* `compressors` - An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance.

<!-- ZH -->
* `compressors` - 压缩器数组或逗号分隔的字符串，用于为该客户端与 mongod/mongos 实例之间的通信启用网络压缩。

<!-- EN -->
* `connectTimeoutMS` - The time in milliseconds to attempt a connection before timing out. Default: `30000`.

<!-- ZH -->
* `connectTimeoutMS` - 尝试连接多久（毫秒）后超时。默认：`30000`。

<!-- EN -->
* `database` - Database name.

<!-- ZH -->
* `database` - 数据库名。

<!-- EN -->
* `directConnection` - Allow a driver to force a Single topology type with a connection string containing one host.

<!-- ZH -->
* `directConnection` - 允许驱动在连接字符串只含一个主机时强制使用 Single 拓扑类型。

<!-- EN -->
* `driver` - The driver object. Defaults to `require("mongodb")`.

<!-- ZH -->
* `driver` - 驱动对象。默认是 `require("mongodb")`。

<!-- EN -->
* `family` - IP family.

<!-- ZH -->
* `family` - IP 协议族。

<!-- EN -->
* `forceServerObjectId` - Force server to assign \_id values instead of driver. Default: `false`.

<!-- ZH -->
* `forceServerObjectId` - 强制由服务器而不是驱动来分配 \_id 值。默认：`false`。

<!-- EN -->
* `host` - Database host.

<!-- ZH -->
* `host` - 数据库主机。

<!-- EN -->
* `hostReplicaSet` - Database host replica set.

<!-- ZH -->
* `hostReplicaSet` - 数据库主机副本集。

<!-- EN -->
* `ignoreUndefined` - Specify if the BSON serializer should ignore undefined fields. Default: `false`.

<!-- ZH -->
* `ignoreUndefined` - 指定 BSON 序列化器是否应忽略 undefined 字段。默认：`false`。

<!-- EN -->
* `localThresholdMS` - The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances.

<!-- ZH -->
* `localThresholdMS` - 在多个合适的 MongoDB 实例之间做选择时延迟窗口的大小（毫秒）。

<!-- EN -->
* `maxStalenessSeconds` - Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. Minimum is 90 seconds.

<!-- ZH -->
* `maxStalenessSeconds` - 指定从节点可以落后多少秒，之后客户端就不再用它执行读操作。最小为 90 秒。

<!-- EN -->
* `minPoolSize` - The minimum number of connections in the connection pool.

<!-- ZH -->
* `minPoolSize` - 连接池中的最小连接数。

<!-- EN -->
* `monitorCommands` - Enable command monitoring for this client.

<!-- ZH -->
* `monitorCommands` - 为该客户端启用命令监控。

<!-- EN -->
* `noDelay` - TCP Connection no delay.

<!-- ZH -->
* `noDelay` - TCP 连接无延迟。

<!-- EN -->
* `password` - Database password.

<!-- ZH -->
* `password` - 数据库密码。

<!-- EN -->
* `pkFactory` - A primary key factory object for generation of custom \_id keys.

<!-- ZH -->
* `pkFactory` - 用于生成自定义 \_id 键的主键工厂对象。

<!-- EN -->
* `poolSize` - Maximum number of connections in the connection pool. Mapped to the MongoDB driver's `maxPoolSize` option.

<!-- ZH -->
* `poolSize` - 连接池中的最大连接数。映射到 MongoDB 驱动的 `maxPoolSize` 选项。

<!-- EN -->
* `port` - Database host port. Default mongodb port is `27017`.

<!-- ZH -->
* `port` - 数据库主机端口。mongodb 默认端口是 `27017`。

<!-- EN -->
* `promoteBuffers` - Promotes Binary BSON values to native Node Buffers. Default: `false`.

<!-- ZH -->
* `promoteBuffers` - 把二进制 BSON 值提升为原生 Node Buffer。默认：`false`。

<!-- EN -->
* `promoteLongs` - Promotes Long values to number if they fit inside the 53-bit resolution. Default: `true`.

<!-- ZH -->
* `promoteLongs` - 如果 Long 值能放进 53 位精度，就把它提升为 number。默认：`true`。

<!-- EN -->
* `promoteValues` - Promotes BSON values to native types where possible, set to false to only receive wrapper types. Default: `true`.

<!-- ZH -->
* `promoteValues` - 尽可能把 BSON 值提升为原生类型，设为 false 则只接收包装类型。默认：`true`。

<!-- EN -->
* `proxyHost` - Configures a Socks5 proxy host used for creating TCP connections.

<!-- ZH -->
* `proxyHost` - 配置用于创建 TCP 连接的 Socks5 代理主机。

<!-- EN -->
* `proxyPassword` - Configures a Socks5 proxy password when the proxy requires username/password authentication.

<!-- ZH -->
* `proxyPassword` - 当代理要求用户名/密码认证时，配置 Socks5 代理密码。

<!-- EN -->
* `proxyPort` - Configures a Socks5 proxy port used for creating TCP connections.

<!-- ZH -->
* `proxyPort` - 配置用于创建 TCP 连接的 Socks5 代理端口。

<!-- EN -->
* `proxyUsername` - Configures a Socks5 proxy username when the proxy requires username/password authentication.

<!-- ZH -->
* `proxyUsername` - 当代理要求用户名/密码认证时，配置 Socks5 代理用户名。

<!-- EN -->
* `raw` - Return document results as raw BSON buffers. Default: `false`.

<!-- ZH -->
* `raw` - 把文档结果作为原始 BSON 缓冲区返回。默认：`false`。

<!-- EN -->
* `readConcern` - Specify a read concern for the collection.

<!-- ZH -->
* `readConcern` - 为集合指定读关注（read concern）。

<!-- EN -->
* `readPreference` - The preferred read preference.

<!-- ZH -->
* `readPreference` - 首选的读偏好。

<!-- EN -->
  * `ReadPreference.PRIMARY`
  * `ReadPreference.PRIMARY_PREFERRED`
  * `ReadPreference.SECONDARY`
  * `ReadPreference.SECONDARY_PREFERRED`
  * `ReadPreference.NEAREST`

<!-- ZH -->
  * `ReadPreference.PRIMARY`
  * `ReadPreference.PRIMARY_PREFERRED`
  * `ReadPreference.SECONDARY`
  * `ReadPreference.SECONDARY_PREFERRED`
  * `ReadPreference.NEAREST`

<!-- EN -->
* `readPreferenceTags` - Specifies the tags document as a comma-separated list of colon-separated key-value pairs.

<!-- ZH -->
* `readPreferenceTags` - 以逗号分隔的、冒号分隔的键值对列表形式指定 tags 文档。

<!-- EN -->
* `replicaSet` - Specifies the name of the replica set, if the mongod is a member of a replica set.

<!-- ZH -->
* `replicaSet` - 如果 mongod 是副本集成员，指定副本集的名称。

<!-- EN -->
* `retryWrites` - Enable retryable writes.

<!-- ZH -->
* `retryWrites` - 启用可重试写入。

<!-- EN -->
* `serializeFunctions` - Serialize functions on any object. Default: `false`.

<!-- ZH -->
* `serializeFunctions` - 序列化任何对象上的函数。默认：`false`。

<!-- EN -->
* `socketTimeoutMS` - The time in milliseconds to attempt a send or receive on a socket before the attempt times out. Default: `360000`.

<!-- ZH -->
* `socketTimeoutMS` - 在 socket 上尝试发送或接收多久（毫秒）后超时。默认：`360000`。

<!-- EN -->
* `tls` - Enables or disables TLS/SSL for the connection. Default: `false`.

<!-- ZH -->
* `tls` - 为连接启用或禁用 TLS/SSL。默认：`false`。

<!-- EN -->
* `tlsAllowInvalidCertificates` - Bypasses validation of the certificates presented by the mongod/mongos instance. Default: `false`.

<!-- ZH -->
* `tlsAllowInvalidCertificates` - 跳过对 mongod/mongos 实例所提供证书的校验。默认：`false`。

<!-- EN -->
* `tlsCAFile` - Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority.

<!-- ZH -->
* `tlsCAFile` - 指定包含证书颁发机构根证书链的本地 .pem 文件位置。

<!-- EN -->
* `tlsCertificateKeyFile` - Specifies the location of a local .pem file that contains the client's TLS/SSL certificate and key.

<!-- ZH -->
* `tlsCertificateKeyFile` - 指定包含客户端 TLS/SSL 证书和密钥的本地 .pem 文件位置。

<!-- EN -->
* `tlsCertificateKeyFilePassword` - Specifies the password to decrypt the `tlsCertificateKeyFile`.

<!-- ZH -->
* `tlsCertificateKeyFilePassword` - 指定用于解密 `tlsCertificateKeyFile` 的密码。

<!-- EN -->
* `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.

<!-- ZH -->
* `url` - 建立连接的连接 url。请注意，其他数据源选项会覆盖从 url 中设置的参数。

<!-- EN -->
* `username` - Database username.

<!-- ZH -->
* `username` - 数据库用户名。

<!-- EN -->
* `writeConcern` - A MongoDB WriteConcern, which describes the level of acknowledgement requested from MongoDB for write operations.

<!-- ZH -->
* `writeConcern` - 一个 MongoDB WriteConcern，描述对写操作向 MongoDB 请求的确认级别。

<!-- EN -->
Additional options can be added to the `extra` object and will be passed directly to the client library. See more in `mongodb`'s documentation for [Connection Options](https://mongodb-node.netlify.app/docs/drivers/node/current/connect/connection-options/).

<!-- ZH -->
更多选项可以加到 `extra` 对象中，它们会被直接传给客户端库。更多内容见 `mongodb` 关于[连接选项](https://mongodb-node.netlify.app/docs/drivers/node/current/connect/connection-options/)的文档。

<!-- EN -->
## Defining entities and columns

<!-- ZH -->
## 定义实体与列

<!-- EN -->
Defining entities and columns is almost the same as in relational databases, the main difference is that you must use `@ObjectIdColumn` instead of `@PrimaryColumn` or `@PrimaryGeneratedColumn`.

<!-- ZH -->
定义实体和列与关系型数据库中几乎相同，主要区别是你必须使用 `@ObjectIdColumn` 而不是 `@PrimaryColumn` 或 `@PrimaryGeneratedColumn`。

<!-- EN -->
Simple entity example:

<!-- ZH -->
简单实体示例：

<!-- EN -->
```typescript
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    _id: ObjectId

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    _id: ObjectId

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- EN -->
And this is how you bootstrap the app:

<!-- ZH -->
这是启动应用的方式：

<!-- EN -->
```typescript
import { DataSource } from "typeorm"

const myDataSource = new DataSource({
    type: "mongodb",
    host: "localhost",
    port: 27017,
    database: "test",
})
```

<!-- ZH -->
```typescript
import { DataSource } from "typeorm"

const myDataSource = new DataSource({
    type: "mongodb",
    host: "localhost",
    port: 27017,
    database: "test",
})
```

<!-- EN -->
## Defining subdocuments (embed documents)

<!-- ZH -->
## 定义子文档（嵌入文档）

<!-- EN -->
Since MongoDB stores objects and objects inside objects (or documents inside documents), you can do the same in TypeORM:

<!-- ZH -->
由于 MongoDB 存储对象以及对象中的对象（或者说文档中的文档），你在 TypeORM 中也可以这样做：

<!-- EN -->
```typescript
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

export class Profile {
    @Column()
    about: string

    @Column()
    education: string

    @Column()
    career: string
}
```

<!-- ZH -->
```typescript
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

export class Profile {
    @Column()
    about: string

    @Column()
    education: string

    @Column()
    career: string
}
```

<!-- EN -->
```typescript
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

export class Photo {
    @Column()
    url: string

    @Column()
    description: string

    @Column()
    size: number

    constructor(url: string, description: string, size: number) {
        this.url = url
        this.description = description
        this.size = size
    }
}
```

<!-- ZH -->
```typescript
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

export class Photo {
    @Column()
    url: string

    @Column()
    description: string

    @Column()
    size: number

    constructor(url: string, description: string, size: number) {
        this.url = url
        this.description = description
        this.size = size
    }
}
```

<!-- EN -->
```typescript
import { Entity, ObjectId, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectId

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column((type) => Profile)
    profile: Profile

    @Column((type) => Photo)
    photos: Photo[]
}
```

<!-- ZH -->
```typescript
import { Entity, ObjectId, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectId

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column((type) => Profile)
    profile: Profile

    @Column((type) => Photo)
    photos: Photo[]
}
```

<!-- EN -->
If you save this entity:

<!-- ZH -->
如果你保存这个实体：

<!-- EN -->
```typescript
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.profile = new Profile()
user.profile.about = "About Trees and Me"
user.profile.education = "Tree School"
user.profile.career = "Lumberjack"
user.photos = [
    new Photo("me-and-trees.jpg", "Me and Trees", 100),
    new Photo("me-and-chakram.jpg", "Me and Chakram", 200),
]

await myDataSource.manager.save(user)
```

<!-- ZH -->
```typescript
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.profile = new Profile()
user.profile.about = "About Trees and Me"
user.profile.education = "Tree School"
user.profile.career = "Lumberjack"
user.photos = [
    new Photo("me-and-trees.jpg", "Me and Trees", 100),
    new Photo("me-and-chakram.jpg", "Me and Chakram", 200),
]

await myDataSource.manager.save(user)
```

<!-- EN -->
The following document will be saved in the database:

<!-- ZH -->
数据库中会保存如下文档：

<!-- EN -->
```json
{
    "firstName": "Timber",
    "lastName": "Saw",
    "profile": {
        "about": "About Trees and Me",
        "education": "Tree School",
        "career": "Lumberjack"
    },
    "photos": [
        {
            "url": "me-and-trees.jpg",
            "description": "Me and Trees",
            "size": 100
        },
        {
            "url": "me-and-chakram.jpg",
            "description": "Me and Chakram",
            "size": 200
        }
    ]
}
```

<!-- ZH -->
```json
{
    "firstName": "Timber",
    "lastName": "Saw",
    "profile": {
        "about": "About Trees and Me",
        "education": "Tree School",
        "career": "Lumberjack"
    },
    "photos": [
        {
            "url": "me-and-trees.jpg",
            "description": "Me and Trees",
            "size": 100
        },
        {
            "url": "me-and-chakram.jpg",
            "description": "Me and Chakram",
            "size": 200
        }
    ]
}
```

<!-- EN -->
## Selecting specific fields with `select`

<!-- ZH -->
## 用 `select` 选取特定字段

<!-- EN -->
You can project only the fields you need using the `select` option on `find*` methods. The object is translated into a MongoDB [projection](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/); nested embedded documents use object syntax and are flattened to dot-path projections.

<!-- ZH -->
你可以在 `find*` 方法上用 `select` 选项只投影出你需要的字段。该对象会被转换成 MongoDB 的[投影](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/)；嵌套的嵌入文档使用对象语法，并被扁平化为点路径投影。

<!-- EN -->
```typescript
const products = await myDataSource.getMongoRepository(Product).find({
    select: { name: true, specs: { weight: true } },
})
```

<!-- ZH -->
```typescript
const products = await myDataSource.getMongoRepository(Product).find({
    select: { name: true, specs: { weight: true } },
})
```

<!-- EN -->
The example above returns each product with only `name` and `specs.weight` populated (plus the entity id). Unknown property names, whether at the top level or inside an embedded document, throw `EntityPropertyNotFoundError` — matching the behavior of SQL drivers.

<!-- ZH -->
上面的示例返回的每个 product 只填充 `name` 和 `specs.weight`（外加实体 id）。未知的属性名——无论在顶层还是在嵌入文档内部——都会抛出 `EntityPropertyNotFoundError`，这与 SQL 驱动的行为一致。

<!-- EN -->
## Using `MongoEntityManager` and `MongoRepository`

<!-- ZH -->
## 使用 `MongoEntityManager` 与 `MongoRepository`

<!-- EN -->
You can use the majority of methods inside the `EntityManager` (except for RDBMS-specific, like `query` and `transaction`). For example:

<!-- ZH -->
你可以使用 `EntityManager` 中的大部分方法（RDBMS 专属的除外，比如 `query` 和 `transaction`）。例如：

<!-- EN -->
```typescript
const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- EN -->
For MongoDB there is also a separate `MongoEntityManager` which extends `EntityManager`.

<!-- ZH -->
对 MongoDB 还有一个单独的 `MongoEntityManager`，它继承自 `EntityManager`。

<!-- EN -->
```typescript
const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- EN -->
Just like separate like `MongoEntityManager` there is a `MongoRepository` with extended `Repository`:

<!-- ZH -->
就像有单独的 `MongoEntityManager` 一样，也有一个扩展了 `Repository` 的 `MongoRepository`：

<!-- EN -->
```typescript
const timber = await myDataSource.getMongoRepository(User).findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.getMongoRepository(User).findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- EN -->
Use Advanced options in find():

<!-- ZH -->
在 find() 中使用进阶选项：

<!-- EN -->
Equal:

<!-- ZH -->
Equal：

<!-- EN -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $eq: "Timber" },
    },
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $eq: "Timber" },
    },
})
```

<!-- EN -->
LessThan:

<!-- ZH -->
LessThan：

<!-- EN -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        age: { $lt: 60 },
    },
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        age: { $lt: 60 },
    },
})
```

<!-- EN -->
In:

<!-- ZH -->
In：

<!-- EN -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $in: ["Timber", "Zhang"] },
    },
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $in: ["Timber", "Zhang"] },
    },
})
```

<!-- EN -->
Not in:

<!-- ZH -->
Not in：

<!-- EN -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $not: { $in: ["Timber", "Zhang"] } },
    },
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $not: { $in: ["Timber", "Zhang"] } },
    },
})
```

<!-- EN -->
Or:

<!-- ZH -->
Or：

<!-- EN -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        $or: [{ firstName: "Timber" }, { firstName: "Zhang" }],
    },
})
```

<!-- ZH -->
```typescript
const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        $or: [{ firstName: "Timber" }, { firstName: "Zhang" }],
    },
})
```

<!-- EN -->
Querying subdocuments

<!-- ZH -->
查询子文档

<!-- EN -->
```typescript
const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "profile.education": { $eq: "Tree School" },
    },
})
```

<!-- ZH -->
```typescript
const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "profile.education": { $eq: "Tree School" },
    },
})
```

<!-- EN -->
Querying Array of subdocuments

<!-- ZH -->
查询子文档数组

<!-- EN -->
```typescript
// Query users with photos of size less than 500
const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "photos.size": { $lt: 500 },
    },
})
```

<!-- ZH -->
```typescript
// 查询照片大小小于 500 的用户
const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "photos.size": { $lt: 500 },
    },
})
```

<!-- EN -->
Both `MongoEntityManager` and `MongoRepository` contain a lot of useful MongoDB-specific methods:

<!-- ZH -->
`MongoEntityManager` 和 `MongoRepository` 都包含大量有用的 MongoDB 专属方法：

<!-- EN -->
### `createCursor`

<!-- ZH -->
### `createCursor`

<!-- EN -->
Create a cursor for a query that can be used to iterate over results from MongoDB.

<!-- ZH -->
为查询创建一个游标，可用于遍历来自 MongoDB 的结果。

<!-- EN -->
### `createEntityCursor`

<!-- ZH -->
### `createEntityCursor`

<!-- EN -->
Create a cursor for a query that can be used to iterate over results from MongoDB. This returns a modified version of the cursor that transforms each result into Entity models.

<!-- ZH -->
为查询创建一个游标，可用于遍历来自 MongoDB 的结果。它返回游标的一个修改版本，会把每个结果转换成实体模型。

<!-- EN -->
### `aggregate`

<!-- ZH -->
### `aggregate`

<!-- EN -->
Execute an aggregation framework pipeline against the collection.

<!-- ZH -->
针对集合执行聚合框架管道。

<!-- EN -->
### `bulkWrite`

<!-- ZH -->
### `bulkWrite`

<!-- EN -->
Perform a bulkWrite operation without a fluent API.

<!-- ZH -->
不使用流式 API 执行 bulkWrite 操作。

<!-- EN -->
### `count`

<!-- ZH -->
### `count`

<!-- EN -->
Count the number of matching documents in the db to a query.

<!-- ZH -->
统计数据库中匹配某查询的文档数量。

<!-- EN -->
### `countDocuments`

<!-- ZH -->
### `countDocuments`

<!-- EN -->
Count the number of matching documents in the db to a query.

<!-- ZH -->
统计数据库中匹配某查询的文档数量。

<!-- EN -->
### `createCollectionIndex`

<!-- ZH -->
### `createCollectionIndex`

<!-- EN -->
Create an index on the db and collection.

<!-- ZH -->
在数据库和集合上创建一个索引。

<!-- EN -->
### `createCollectionIndexes`

<!-- ZH -->
### `createCollectionIndexes`

<!-- EN -->
Create multiple indexes in the collection. Index specifications are defined at [createIndexes](http://docs.mongodb.org/manual/reference/command/createIndexes/).

<!-- ZH -->
在集合中创建多个索引。索引规范定义见 [createIndexes](http://docs.mongodb.org/manual/reference/command/createIndexes/)。

<!-- EN -->
### `deleteMany`

<!-- ZH -->
### `deleteMany`

<!-- EN -->
Delete multiple documents on MongoDB.

<!-- ZH -->
在 MongoDB 上删除多个文档。

<!-- EN -->
### `deleteOne`

<!-- ZH -->
### `deleteOne`

<!-- EN -->
Delete a document on MongoDB.

<!-- ZH -->
在 MongoDB 上删除一个文档。

<!-- EN -->
### `distinct`

<!-- ZH -->
### `distinct`

<!-- EN -->
The distinct command returns a list of distinct values for the given key across a collection.

<!-- ZH -->
distinct 命令返回给定键在某个集合中的不同值列表。

<!-- EN -->
### `dropCollectionIndex`

<!-- ZH -->
### `dropCollectionIndex`

<!-- EN -->
Drops an index from this collection.

<!-- ZH -->
从该集合中删除一个索引。

<!-- EN -->
### `dropCollectionIndexes`

<!-- ZH -->
### `dropCollectionIndexes`

<!-- EN -->
Drops all indexes from the collection.

<!-- ZH -->
从集合中删除所有索引。

<!-- EN -->
### `findOneAndDelete`

<!-- ZH -->
### `findOneAndDelete`

<!-- EN -->
Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.

<!-- ZH -->
在一个原子操作中查找并删除文档，操作期间需要写锁。

<!-- EN -->
### `findOneAndReplace`

<!-- ZH -->
### `findOneAndReplace`

<!-- EN -->
Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.

<!-- ZH -->
在一个原子操作中查找并替换文档，操作期间需要写锁。

<!-- EN -->
### `findOneAndUpdate`

<!-- ZH -->
### `findOneAndUpdate`

<!-- EN -->
Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.

<!-- ZH -->
在一个原子操作中查找并更新文档，操作期间需要写锁。

<!-- EN -->
### `geoHaystackSearch`

<!-- ZH -->
### `geoHaystackSearch`

<!-- EN -->
Execute a geo search using a geo haystack index on a collection.

<!-- ZH -->
使用集合上的 geo haystack 索引执行地理搜索。

<!-- EN -->
### `geoNear`

<!-- ZH -->
### `geoNear`

<!-- EN -->
Execute the geoNear command to search for items in the collection.

<!-- ZH -->
执行 geoNear 命令，在集合中搜索条目。

<!-- EN -->
### `group`

<!-- ZH -->
### `group`

<!-- EN -->
Run a group command across a collection.

<!-- ZH -->
跨集合运行 group 命令。

<!-- EN -->
### `collectionIndexes`

<!-- ZH -->
### `collectionIndexes`

<!-- EN -->
Retrieve all the indexes of the collection.

<!-- ZH -->
取回集合的所有索引。

<!-- EN -->
### `collectionIndexExists`

<!-- ZH -->
### `collectionIndexExists`

<!-- EN -->
Retrieve if an index exists on the collection

<!-- ZH -->
取回集合上是否存在某个索引

<!-- EN -->
### `collectionIndexInformation`

<!-- ZH -->
### `collectionIndexInformation`

<!-- EN -->
Retrieve this collection's index info.

<!-- ZH -->
取回该集合的索引信息。

<!-- EN -->
### `initializeOrderedBulkOp`

<!-- ZH -->
### `initializeOrderedBulkOp`

<!-- EN -->
Initiate an In order bulk write operation; operations will be serially executed in the order they are added, creating a new operation for each switch in types.

<!-- ZH -->
发起一个有序批量写操作；各操作会按添加顺序串行执行，每遇到类型切换就创建一个新操作。

<!-- EN -->
### `initializeUnorderedBulkOp`

<!-- ZH -->
### `initializeUnorderedBulkOp`

<!-- EN -->
Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.

<!-- ZH -->
发起一个无序批量写操作。所有操作会被缓冲成 insert/update/remove 命令并乱序执行。

<!-- EN -->
### `insertMany`

<!-- ZH -->
### `insertMany`

<!-- EN -->
Insert an array of documents into MongoDB.

<!-- ZH -->
向 MongoDB 插入一个文档数组。

<!-- EN -->
### `insertOne`

<!-- ZH -->
### `insertOne`

<!-- EN -->
Insert a single document into MongoDB.

<!-- ZH -->
向 MongoDB 插入单个文档。

<!-- EN -->
### `isCapped`

<!-- ZH -->
### `isCapped`

<!-- EN -->
Return if the collection is a capped collection.

<!-- ZH -->
返回该集合是否为固定大小（capped）集合。

<!-- EN -->
### `listCollectionIndexes`

<!-- ZH -->
### `listCollectionIndexes`

<!-- EN -->
Get the list of all indexes information for the collection.

<!-- ZH -->
获取该集合所有索引信息的列表。

<!-- EN -->
### `parallelCollectionScan`

<!-- ZH -->
### `parallelCollectionScan`

<!-- EN -->
Return N number of parallel cursors for a collection allowing parallel reading of the entire collection. There are no ordering guarantees for returned results

<!-- ZH -->
为集合返回 N 个并行游标，允许并行读取整个集合。返回结果不保证顺序

<!-- EN -->
### `reIndex`

<!-- ZH -->
### `reIndex`

<!-- EN -->
Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.

<!-- ZH -->
重建集合上的所有索引 警告：reIndex 是阻塞操作（索引在前台重建），对大集合会很慢。

<!-- EN -->
### `rename`

<!-- ZH -->
### `rename`

<!-- EN -->
Change the name of an existing collection.

<!-- ZH -->
修改已有集合的名称。

<!-- EN -->
### `replaceOne`

<!-- ZH -->
### `replaceOne`

<!-- EN -->
Replace a document on MongoDB.

<!-- ZH -->
在 MongoDB 上替换一个文档。

<!-- EN -->
### `updateMany`

<!-- ZH -->
### `updateMany`

<!-- EN -->
Update multiple documents within the collection based on the filter.

<!-- ZH -->
根据过滤条件更新集合中的多个文档。

<!-- EN -->
### `updateOne`

<!-- ZH -->
### `updateOne`

<!-- EN -->
Update a single document within the collection based on the filter.

<!-- ZH -->
根据过滤条件更新集合中的单个文档。
