whereJsonContains / whereJsonHasKey
Description
Conditions on PostgreSQL JSON columns:
| Method | SQL | True when |
|---|---|---|
whereJsonContains | CAST(column AS jsonb) @> CAST(:value AS jsonb) | the document contains value |
whereJsonHasKey | CAST(column AS jsonb) ? :key | the object has the top-level key (or the array has the string element) |
- "Contains" is PostgreSQL's
@>:{ "role": "admin" }is contained in{ "role": "admin", "age": 30 }, nested objects are matched partially too, and["a"]is contained in["a", "b"]. valueis serialized withJSON.stringify;undefined(or a function) throws aTypeError.- Works with
jsonb,jsonandsimple-jsoncolumns: the column is cast tojsonb. For ajsonbcolumn the cast is a no-op that PostgreSQL drops, so a GIN index (CREATE INDEX … USING GIN (meta)) is still used. Ajsoncolumn can't have such an index. whereJsonHasKeyuses the?operator, not thejsonb_exists()function: only the operator can use the index.
PostgreSQL only (and compatible databases such as CockroachDB). TypeORM's simple-json columns (JSON stored as text) work too, as the cast parses the text, but without an index.
Available on SelectQueryBuilder, UpdateQueryBuilder, DeleteQueryBuilder and SoftDeleteQueryBuilder (softDelete(), restore()).
Signature
whereJsonContains(field: string, value: unknown): this
andWhereJsonContains(field: string, value: unknown): this
orWhereJsonContains(field: string, value: unknown): this
whereJsonHasKey(field: string, key: string): this
andWhereJsonHasKey(field: string, key: string): this
orWhereJsonHasKey(field: string, key: string): this
Arguments
- field: string: JSON column, e.g.
'user.metadata'(quoted as"user"."metadata"), or a JSON expression such astableHelper<User>('user').json((u) => u.metadata.settings), which is used as is. - value: unknown: Part of the document to look for: an object, an array, or a scalar.
- key: string: Top-level key to look for.
Usage
// WHERE CAST("user"."metadata" AS jsonb) @> CAST($1 AS jsonb), $1 = '{"role":"admin"}'
query.whereJsonContains('user.metadata', { role: 'admin' })
// nested objects and arrays are matched partially
query.whereJsonContains('user.metadata', { settings: { theme: 'dark' } })
query.whereJsonContains('article.meta', { flags: ['featured'] })
// WHERE CAST("user"."metadata" AS jsonb) ? $1, $1 = 'settings'
query.whereJsonHasKey('user.metadata', 'settings')
// a key of a nested object: pass a JSON expression as the field
// WHERE CAST("user"."metadata" -> 'settings' AS jsonb) ? $1
const u = tableHelper<UserEntity>('user');
query.whereJsonHasKey(u.json((r) => r.metadata.settings), 'theme')
For a typesafe version that takes the column from an entity property, see whereJsonContainsTyped.