---
title: 查询条件
---

来源：https://mikro-orm.io/docs/query-conditions

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

当你想构造复杂查询时，很容易写出一大堆充满花括号的样板代码：

```ts
const res = await orm.em.find(Author, {
  $and: [
    { id: { $in: [1, 2, 7] } },
    { id: { $nin: [3, 4] } },
    { id: { $gt: 5 } },
    { id: { $lt: 10 } },
    { id: { $gte: 7 } },
    { id: { $lte: 8 } },
    { id: { $ne: 9 } },
  ],
});
```

对于作用在单个字段上的 AND 条件，你也可以这样写：

```ts
const res = await orm.em.find(Author, {
  id: {
    $in: [1, 2, 7],
    $nin: [3, 4],
    $gt: 5,
    $lt: 10,
    $gte: 7,
    $lte: 8,
    $ne: 9,
  },
});
```

`$in` 还有一种简写形式——直接把数组作为值传入，它会被自动转换：

```ts
const res = await orm.em.find(Author, { favouriteBook: [1, 2, 7] });
```

在数组属性（`type: 'string[]'` 以及其他 `ArrayType` 列）上，`$in` 与 `$nin` 的行为与 MongoDB 一致。数组的列表会匹配整个数组，因此 `{ tags: { $in: [['a', 'b'], ['c']] } }` 会找出 `tags` 等于 `['a', 'b']` 或 `['c']` 的行。扁平列表则匹配其中任意一个元素，因此 `{ tags: ['a', 'b'] }` 会找出 `tags` 中包含 `'a'` 或 `'b'` 的行。SQL 驱动中只有 PostgreSQL 支持扁平列表（它会映射为 `&&` 操作符），其他驱动会抛错。使用 `$eq` 可以精确匹配整个数组。

按主键查找时，可以直接把数组传给 `em.find()`：

```ts
const res = await orm.em.find(Author, [1, 2, 7]);
```

<a id="list-of-supported-operators"></a>
## 支持的操作符列表

<a id="comparison"></a>
### 比较

| operator       | name             | description                                                                                 |
| -------------- | ---------------- | ------------------------------------------------------------------------------------------- |
| `$eq`          | 等于             | 匹配与指定值相等的值。                                                                      |
| `$gt`          | 大于             | 匹配大于指定值的值。                                                                        |
| `$gte`         | 大于等于         | 匹配大于或等于指定值的值。                                                                  |
| `$in`          | 包含             | 匹配数组中指定的任意一个值。                                                                |
| `$lt`          | 小于             | 匹配小于指定值的值。                                                                        |
| `$lte`         | 小于等于         | 匹配小于或等于指定值的值。                                                                  |
| `$ne`          | 不等于           | 匹配所有不等于指定值的值。                                                                  |
| `$nin`         | 不包含           | 不匹配数组中指定的任何一个值。                                                              |
| `$all`         | 全部             | 匹配包含数组中所有指定值的集合（以及 mongo 数组）。                                         |
| `$like`        | like             | 使用 LIKE 操作符                                                                            |
| `$re`          | regexp           | 使用 REGEXP 操作符。参见[下文](#regular-expressions)的说明                                  |
| `$fulltext`    | 全文             | 驱动特定的全文检索函数。参见[下文](#full-text-searching)的前提条件                           |
| `$ilike`       | ilike            | （仅 postgres）                                                                             |
| `$overlap`     | &&               | （仅 postgres）                                                                             |
| `$contains`    | @>               | （仅 postgres）                                                                             |
| `$contained`   | \<@              | （仅 postgres）                                                                             |
| `$hasKey`      | ?                | （仅 postgres）                                                                             |
| `$hasSomeKeys` | ?&#x7c;          | （仅 postgres）                                                                             |
| `$hasKeys`     | ?&               | （仅 postgres）                                                                             |

<a id="logical"></a>
### 逻辑

| operator | description                                                                                             |
| -------- | ------------------------------------------------------------------------------------------------------- |
| `$and`   | 以逻辑 AND 连接查询子句，返回同时满足两个子句条件的全部文档。                                           |
| `$not`   | 取反查询表达式的效果，返回不满足该查询表达式的文档。                                                    |
| `$or`    | 以逻辑 OR 连接查询子句，返回满足任一子句条件的全部文档。                                                |

<a id="collection"></a>
### 集合

除了那些会被翻译为真实 SQL 操作符表达式（例如 `>=`）的常规操作符之外，你还可以使用下面这些集合操作符：

| operator | description                                                     |
| -------- | --------------------------------------------------------------- |
| `$some`  | 找出存在至少一条记录满足条件的集合。                            |
| `$none`  | 找出没有任何记录满足条件的集合。                                |
| `$every` | 找出每一条记录都满足条件的集合。                                |
| `$size`  | 根据关联记录的数量来筛选集合。                                  |
| `$all`   | 找出包含所有给定记录的集合。                                    |

它们会被解析为子查询条件：

```ts
// 找出所有拥有某本名为 `Foo` 的书的作者
const res1 = await em.find(Author, {
  books: { $some: { title: 'Foo' } },
});

// 找出所有没有名为 `Foo` 的书的作者
const res2 = await em.find(Author, {
  books: { $none: { title: 'Foo' } },
});

// 找出所有每一本书都名为 `Foo` 的作者
const res3 = await em.find(Author, {
  books: { $every: { title: 'Foo' } },
});
```

`$all` 操作符接受一个数组，并要求其中每一项都存在于集合中，每一项可以是主键，也可以是一个条件：

```ts
// 找出所有同时拥有名为 `Foo` 和名为 `Bar` 的书的作者
const res = await em.find(Author, {
  books: { $all: [{ title: 'Foo' }, { title: 'Bar' }] },
});
```

空数组不会匹配任何内容，这与 MongoDB 的行为一致。在 mongo 上，`$all` 同样可以作用于数组属性；而在 SQL 驱动中它只支持集合属性——对于数组列请使用 `$contains`。

条件对象也可以为空：

```ts
// 找出所有至少有一本书的作者
const res1 = await em.find(Author, {
  books: { $some: {} },
});

// 找出所有没有书的作者
const res2 = await em.find(Author, {
  books: { $none: {} },
});
```

`$size` 操作符可以根据关联项的数量来筛选实体。它既接受一个数字（精确匹配），也接受一个包含比较操作符的对象：

```ts
// 找出所有没有书的作者
const res1 = await em.find(Author, {
  books: { $size: 0 },
});

// 找出所有恰好有 5 本书的作者
const res2 = await em.find(Author, {
  books: { $size: 5 },
});

// 找出所有至少有 3 本书的作者
const res3 = await em.find(Author, {
  books: { $size: { $gte: 3 } },
});

// 找出所有书数量在 1 到 5 之间的作者
const res4 = await em.find(Author, {
  books: { $size: { $gt: 0, $lte: 5 } },
});
```

<a id="regular-expressions"></a>
## 正则表达式

`$re` 操作符以字符串作为输入值，并且默认使用区分大小写的操作符。如果你想使用 `RegExp` 对象（也就是希望能够设置标志位），那么请直接以字段名进行查询，而不要使用该操作符：

```ts
const res = await em.find(Painter, {
  lastName: /m[oa]net/i, // 或 `new RegExp('m[oa]net', 'i')`
});
```

<a id="full-text-searching"></a>
## 全文检索

全文检索指的是在存储的大量文本数据中搜索某些文本，并返回包含查询中部分或全部词语的结果。相比之下，传统搜索只会返回精确匹配的结果。

各驱动的实现与前提条件各不相同，因此正确地配置字段非常重要。

<a id="postgresql"></a>
### PostgreSQL

PostgreSQL 允许在 pg-vector 类型上执行查询（pg-query）。pg-vector 类型可以是一个列（性能更好），也可以在查询中创建（不会在数据库中产生多余的列）。当使用列时，还支持诸如[自定义 `regconfig` 或 `setweight`](https://www.postgresql.org/docs/current/textsearch-controls.html) 这样的高级功能（默认的 `regconfig` 为 `simple`）。

关于可用的查询方式，请参考 [PostgreSQL 文档](https://www.postgresql.org/docs/current/functions-textsearch.html)。

<Tabs
groupId="postgres-full-text"
defaultValue="as-column"
values={[
{label: '使用列', value: 'as-column'},
{label: '使用索引', value: 'in-query'},
]
}>
<TabItem value="as-column">

```ts title="./entities/Book.ts"
import { FullTextType, WeightedFullTextValue } from '@mikro-orm/postgresql';

@Entity()
export class Book {
  @Property()
  title!: string;

  // 使用默认配置的示例
  @Index({ type: 'fulltext' })
  @Property({ type: FullTextType, onUpdate: book => book.title })
  searchableTitle!: string;

  // 使用自定义 regconfig 的示例
  @Index({ type: 'fulltext' })
  @Property({ type: new FullTextType('english'), onUpdate: book => book.title })
  searchableTitle!: string;

  // 使用权重的示例
  @Index({ type: 'fulltext' })
  @Property({ type: FullTextType, onUpdate: book => ({ A: book.title, B: book.description }) })
  searchableTitle!: WeightedFullTextValue;
}
```

查找结果：`repository.findOne({ searchableTitle: { $fulltext: 'query' } })`。

  </TabItem>
  <TabItem value="in-query">

```ts title="./entities/Book.ts"
@Entity()
export class Book {
  @Index({ type: 'fulltext' })
  @Property()
  title!: string;
}
```

查找结果：`repository.findOne({ title: { $fulltext: 'query' } })`

  </TabItem>
</Tabs>

<a id="mysql-mariadb"></a>
### MySQL、MariaDB

MySQL 与 MariaDB 允许在所有带有全文索引的列上执行全文检索。

关于可用的查询方式，请参考 [MySQL 文档](https://dev.mysql.com/doc/refman/8.0/en/fulltext-boolean.html)或 [MariaDB 文档](https://mariadb.com/kb/en/full-text-index-overview/#in-boolean-mode)。

```ts title="./entities/Book.ts"
@Entity()
export class Book {
  @Index({ type: 'fulltext' })
  @Property()
  title!: string;
}
```

查找结果：`repository.findOne({ title: { $fulltext: 'query' } })`

<a id="mongodb"></a>
### MongoDB

MongoDB 允许在所有带有文本索引的列上执行全文检索。不过在执行全文检索时，它会基于所有带文本索引的字段来挑选匹配项：只能添加一个查询，并且只能位于查询对象的顶层。关于该行为的更多信息，请参考 [MongoDB 文档](https://www.mongodb.com/docs/manual/reference/operator/query/text/#behavior)。

关于可用的查询方式，请参考 [MongoDB 文档](https://www.mongodb.com/docs/manual/reference/operator/query/text/#definition)。

```ts title="./entities/Book.ts"
@Entity()
export class Book {
  @Index({ type: 'fulltext' })
  @Property()
  title!: string;
}
```

<a id="sqlite"></a>
### SQLite

在 SQLite 中，全文检索只能在 [FTS5 虚拟表](https://www.sqlite.org/fts5.html#overview_of_fts5)上执行。MikroORM 无法创建这种表，必须[手动创建](https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization)。简单的表可以用下面这条语句创建：

`CREATE VIRTUAL TABLE <table name> USING fts5(<column1>, <column2>, ...);`

之后就可以按照该表的结构正常创建实体。在 SQLite 中，全文检索并不需要 `@Index`。

关于可用的查询方式，请参考 [SQLite 文档](https://www.sqlite.org/fts5.html#full_text_query_syntax)。

```ts title="./entities/Book.ts"
@Entity()
export class Book {
  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;
}
```

查找结果：`repository.findOne({ title: { $fulltext: 'query' } })`
