---
title: JSON 属性
---

来源：https://mikro-orm.io/docs/json-properties

<a id="defining-json-properties"></a>
## 定义 JSON 属性

在 JSON 属性方面，各个数据库驱动的行为略有不同：有些会自动为你解析值，有些则会把它们作为 JSON 字符串返回。MikroORM 试图通过 [JsonType](./26-custom-types.md#jsontype) 统一这一体验。如果你指定 `type: 'json'`，同样会使用该类型。

```ts
@Entity()
export class Book {

  @Property({ type: 'json', nullable: true })
  meta?: { foo: string; bar: number };

}
```

<a id="querying-by-json-object-properties"></a>
## 按 JSON 对象属性查询

> 你可以按 JSON 对象属性查询。

你可以轻松地按 JSON 对象属性查询：

```ts
const b = await em.findOne(Book, {
  meta: {
    valid: true,
    nested: {
      foo: '123',
      bar: 321,
      deep: {
        baz: 59,
        qux: false,
      },
    },
  },
});
```

会生成如下查询（postgres 中）：

```sql
select "e0".*
from "book" as "e0"
where ("meta"->>'valid')::bool = true
  and "meta"->'nested'->>'foo' = '123'
  and ("meta"->'nested'->>'bar')::float8 = 321
  and ("meta"->'nested'->'deep'->>'baz')::float8 = 59
  and ("meta"->'nested'->'deep'->>'qux')::bool = false
limit 1
```

> 目前所有驱动都受支持（包括 sqlite 与 mongo）。在 postgres 中，如果我们检测到右侧是数字或布尔值，还会尝试对该值做类型转换。

<a id="querying-json-array-elements-with-elemmatch"></a>
## 使用 `$elemMatch` 查询 JSON 数组元素

当某个 JSON 属性存储的是对象数组时，你可以使用 `$elemMatch` 运算符查询单个元素的属性。MikroORM 会生成一个 `EXISTS` 子查询，其中使用平台专属的 JSON 数组迭代（例如 PostgreSQL 的 `jsonb_array_elements`、MySQL/MariaDB 的 `json_table`、SQLite 的 `json_each`）。

类型会根据你的查询值自动推断 —— 无需任何 schema 提示：

```ts
@Entity()
export class Event {

  @Property({ type: 'json', nullable: true })
  tags?: { name: string; priority: number }[];

}

// 查找带有 "typescript" 标签的事件
const events = await em.find(Event, {
  tags: { $elemMatch: { name: 'typescript' } },
});

// 数值条件会被自动转换（例如 postgres 上的 ::float8）
const events = await em.find(Event, {
  tags: { $elemMatch: { priority: { $gt: 5 } } },
});

// 多个条件必须匹配同一个数组元素
const events = await em.find(Event, {
  tags: { $elemMatch: { name: 'typescript', priority: { $gte: 8 } } },
});

// $or/$and/$not 在 $elemMatch 内部同样可用
const events = await em.find(Event, {
  tags: { $elemMatch: { $or: [{ name: 'typescript' }, { name: 'rust' }] } },
});
```

`$elemMatch` 可以通过 `$and` 与数组级运算符组合使用：

```ts
const events = await em.find(Event, {
  $and: [
    { tags: { $elemMatch: { priority: { $gt: 5 } } } },
    { tags: { $contains: [{ name: 'typescript' }] } },
  ],
});
```

> 对于[内嵌数组属性](./23-embeddables.md#array-of-embeddables)，元素级查询无需 `$elemMatch` 即可隐式生效，因为 ORM 从内嵌对象元数据中已知 schema。

<a id="indexes-on-json-properties"></a>
## JSON 属性上的索引

要在 JSON 属性上创建索引，请使用带点路径的实体级 `@Index()` 装饰器：

```ts
@Entity()
@Index({ properties: 'metaData.foo' })
@Index({ properties: ['metaData.foo', 'metaData.bar'] }) // 复合索引
export class Book {

  @Property({ type: 'json', nullable: true })
  metaData?: { foo: string; bar: number };

}
```

在 PostgreSQL 中，这会生成类似如下的查询：

```sql
create index "book_meta_data_foo_index" on "book" (("meta_data"->>'foo'));
```

要创建唯一索引，请使用 `@Unique()` 装饰器：

```ts
@Entity()
@Unique({ properties: 'metaData.foo' })
@Unique({ properties: ['metaData.foo', 'metaData.bar'] }) // 复合唯一索引
export class Book {

  @Property({ type: 'json', nullable: true })
  metaData?: { foo: string; bar: number };

}
```

在 MySQL 中，你也可以显式设置类型：

```ts
@Entity()
@Index({ properties: 'metaData.foo', options: { returning: 'char(200)' } })
export class Book {

  @Property({ type: 'json', nullable: true })
  metaData?: { foo: string; bar: number };

}
```

这会生成类似如下的查询：

```sql
alter table `book`
  add index `book_meta_data_foo_index`((json_value(`meta_data`, '$.foo' returning char(200))));
```

> MariaDB 驱动不支持该特性。
