Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
SDK de Dispositivo Atlas

Lenguaje de consulta de reino

El lenguaje de consulta de dominio (RQL) es un lenguaje de consulta basado en cadenas que restringe las búsquedas al recuperar objetos de un dominio. Los métodos específicos del SDK pasan las consultas al motor de consultas de dominio, que recupera los objetos coincidentes del dominio. La sintaxis del lenguaje de consulta de dominio se basa en NSPredicate.

Las consultas evalúan un predicado para cada objeto de la colección consultada. Si el predicado se resuelve como true, la colección de resultados incluye el objeto.

You can use Realm Query Language in most Realm SDKs with your SDK's filter or query methods. The Swift SDK is the exception, as it uses the NSPredicate query API. Some SDKs also support idiomatic APIs for querying realms in their language.

For further reading on SDK-specific methods for querying realms, see the documentation for your SDK:

The C++ SDK currently implements only a subset of RQL. For examples querying Realm in the C++ SDK, refer to:

Nota

El SDK de Swift no admite Realm Query Language

El SDK de Swift no admite consultas con el lenguaje de consulta Realm. En su lugar, puede usar NSPredicate para consultar Realm. Para ver ejemplos de consultas de Realm en el SDK de Swift, consulte Filtrar datos - SDK de Swift.

You can also use Realm Query Language to browse for data in Realm Studio. Realm Studio is a visual tool to view, edit, and design Realm files.

Many of the examples in this page use a simple data set for a to-do list app. The two Realm object types are Project and Item.

  • An Item has a name, assignee's name, and completed flag. There is also an arbitrary number for priority (higher is more important) and a count of minutes spent working on it.

  • A Project has zero or more Items and an optional quota for minimum number of to-do items expected to be completed.

See the schema for these two classes, Project and Item, below:

public class Item extends RealmObject {
ObjectId id = new ObjectId();
String name;
Boolean isComplete = false;
String assignee;
Integer priority = 0;
Integer progressMinutes = 0;
@LinkingObjects("items")
final RealmResults<Project> projects = null;
}
public class Project extends RealmObject {
ObjectId id = new ObjectId();
String name;
RealmList<Item> items;
Integer quota = null;
}
open class Item(): RealmObject() {
var id: ObjectId = new ObjectId()
@FullText
lateinit var name: String
var isComplete: Boolean = false
var assignee: String? = null
var priority: Int = 0
var progressMinutes: Int = 0
}
open class Project(): RealmObject() {
var id: ObjectId = new ObjectId()
lateinit var name: String
lateinit var items: RealmList<Item>
var quota: Int? = null
}
public class Item : RealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; } = ObjectId.GenerateNewId();
[MapTo("name")]
[Indexed(IndexType.FullText)]
public string Name { get; set; }
[MapTo("isComplete")]
public bool IsComplete { get; set; } = false;
[MapTo("assignee")]
public string Assignee { get; set; }
[MapTo("priority")]
public int Priority { get; set; } = 0;
[MapTo("progressMinutes")]
public int ProgressMinutes { get; set; } = 0;
[MapTo("projects")]
[Backlink(nameof(Project.Items))]
public IQueryable<Project> Projects { get; }
}
public class Project : RealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; } = ObjectId.GenerateNewId();
[MapTo("name")]
public string Name { get; set; }
[MapTo("items")]
public IList<Item> Items { get; }
[MapTo("quota")]
public int Quota { get; set; }
}
const ItemModel = {
name: "Item",
properties: {
id: "objectId",
name: {type: "string", indexed: "full-text"},
isComplete: { type: "bool", default: false },
assignee: "string?",
priority: {
type: "int",
default: 0,
},
progressMinutes: {
type: "int",
default: 0,
},
projects: {
type: "linkingObjects",
objectType: "Project",
property: "items",
},
},
primaryKey: "id",
};
const ProjectModel = {
name: "Project",
properties: {
id: "objectId",
name: "string",
items: "Item[]",
quota: "int?",
},
primaryKey: "id",
};
const ItemModel = {
name: "Item",
properties: {
id: "objectId",
name: {type: "string", indexed: "full-text"},
isComplete: { type: "bool", default: false },
assignee: "string?",
priority: {
type: "int",
default: 0,
},
progressMinutes: {
type: "int",
default: 0,
},
projects: {
type: "linkingObjects",
objectType: "Project",
property: "items",
},
},
primaryKey: "id",
};
const ProjectModel = {
name: "Project",
properties: {
id: "objectId",
name: "string",
items: "Item[]",
quota: "int?",
},
primaryKey: "id",
};
class Item(): RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
@FullText
var name: String = ""
var isComplete: Boolean = false
var assignee: String? = null
var priority: Int = 0
var progressMinutes: Int = 0
}
class Project(): RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var name: String = ""
var items: RealmList<Item> = realmListOf<Item>()
var quota: Int? = null
}
part 'models.realm.dart';
@RealmModel()
class _Project {
@MapTo("_id")
@PrimaryKey()
late ObjectId id;
late String name;
late List<_Item> items;
int? quota;
}
@RealmModel()
class _Item {
@MapTo("_id")
@PrimaryKey()
late ObjectId id;
@Indexed(RealmIndexType.fullText)
late String name;
bool isComplete = false;
String? assignee;
int priority = 0;
int progressMinutes = 0;
}

Los filtros consisten en expresiones dentro de un predicado. Una expresión consta de uno de los siguientes:

  • The name of a property of the object currently being evaluated.

  • Un operador y hasta dos expresiones de argumento. Por ejemplo, en la expresión A + B, A + B es una expresión, pero A y B también son expresiones de argumento para el operador +.

  • A value, such as a string ('hello') or a number (5).

"progressMinutes > 1 AND assignee == $0", "Ali"

Create parameterized queries to interpolate variables into prepared Realm Query Language statements. The syntax for interpolated variables is $<int>, starting at 0. Pass the positional arguments as additional arguments to Realm SDK methods that use Realm Query Language.

Include just one parameter with $0.

"progressMinutes > 1 AND assignee == $0", "Ali"

Incluye múltiples parámetros con números enteros ascendentes a partir de $0.

"progressMinutes > $0 AND assignee == $1", 1, "Alex"

The following table shows how a query should be formatted when serialized and parameterized for the following data types:

Tipo
Parameterized Example
Serialized Example
Nota

Booleano

"setting == $0", false

"configuración == falso"

true o false valores.

"name == $0", "George"

"name == 'George'"

Applies to string and char data type.

"edad > $0", 5.50

"edad > 5,50"

Applies to int, short, long, double, Decimal128, and float data types.

"date < $0", dateObject

"date < 2021-02-20@17:30:15:0"

For parameterized date queries, you must pass in a date object. For serialized date queries, you can represented the date in the following formats:

  • Como fecha y hora explícitas: AAAA-MM-DD@HH:mm:ss:nn (año-mes-día@horas:minutos:segundos:nanosegundos)

  • As a datetime relative to the Unix epoch- Ts:n (T, designates the start of the time; s, seconds; n, nanoseconds)

  • Parameterized Date object

"_id == $0", oidValue

"_id == oid(507f1f77bcf86cd799439011)"

For parameterized ObjectId queries, you must pass in an ObjectId. For serialized ObjectId queries, the string representation is oid(<ObjectId String>).

"id == $0", uuidValue

"id == uuid(d1b186e1-e9e0-4768-a1a7-c492519d47ee)"

Para queries UUID parametrizadas, debes enviar un UUID. Para consultas UUID serializadas, la representación en cadena es uuid(<UUID String>).

Binario

"value == $0", "binary"

"value == 'binary'"

Para caracteres ASCII, RQL serializa el valor binario como una cadena, entre comillas. Para caracteres no imprimibles, RQL serializa el valor binario a un valor de base 64.

"ANY items.name == {$0, $1}", "milk", "bread"

"ANY items.name == {'milk', 'bread'}"

Applies for list, collections, and sets. A parameterized value should be used for each member of the list.

RealmObject

"ANY items == $0", obj("Item", oid(6489f036f7bd0546377303ab))

"ANY items == obj('Item', oid(6489f036f7bd0546377303ab))"

Para pasar un RealmObject, necesita la clase y la clave principal del objeto.

Al referirse a la propiedad de un objeto, se puede utilizar la notación de puntos para referirse a las propiedades secundarias de ese objeto. Incluso se puede hacer referencia a las propiedades de objetos incrustados y relaciones con la notación de puntos.

For example, consider a query on an object with a workplace property that refers to a Workplace object. The Workplace object has an embedded object property, address. You can chain dot notations to refer to the zipcode property of that address:

"workplace.address.zipcode == 10019"

Realm Query Language include the nil type to represent a null pointer. You can either reference nil directly in your queries or with a parameterized query. If you're using a parameterized query, each SDK maps its respective null pointer to nil.

"assignee == nil"
// comparison to language null pointer
"assignee == $0", null

The most straightforward operation in a search is to compare values.

Importante

Types Must Match

El tipo en ambos lados del operador debe ser equivalente. Por ejemplo, comparar un ObjectId con una cadena generará un error de precondición con un mensaje como este:

"Expected object of type object id for property 'id' on object of type
'User', but received: 11223344556677889900aabb (Invalid value)"

Puede comparar cualquier tipo numérico con cualquier otro tipo numérico, incluidos decimal, float y Decimal128.

Operador
Descripción

BETWEEN {number1, number2}

Evaluates to true if the left-hand numerical or date expression is between or equal to the right-hand range. For dates, this evaluates to true if the left-hand date is within the right-hand date range.

==, =

Evaluates to true if the left-hand expression is equal to the right-hand expression.

>

Evaluates to true if the left-hand numerical or date expression is greater than the right-hand numerical or date expression. For dates, this evaluates to true if the left-hand date is later than the right-hand date.

>=

Evaluates to true if the left-hand numerical or date expression is greater than or equal to the right-hand numerical or date expression. For dates, this evaluates to true if the left-hand date is later than or the same as the right-hand date.

IN

Evaluates to true if the left-hand expression is in the right-hand list. This is equivalent to and used as a shorthand for == ANY.

<

Devuelve true si la expresión numérica o de fecha de la izquierda es menor que la expresión numérica o de fecha de la derecha. Para fechas, esto da como resultado true si la fecha de la izquierda es anterior a la fecha de la derecha.

<=

Se evalúa como true si la expresión numérica de la izquierda es menor o igual que la de la derecha. Para las fechas, se evalúa como true si la fecha de la izquierda es anterior o igual a la de la derecha.

!=, <>

Evaluates to true if the left-hand expression is not equal to the right-hand expression.

Ejemplo

El siguiente ejemplo usa los operadores de comparación del Realm Query Language para:

  • Find high priority to-do items by comparing the value of the priority property value with a threshold number, above which priority can be considered high.

  • Find long-running to-do items by seeing if the progressMinutes property is at or above a certain value.

  • Find unassigned to-do items by finding items where the assignee property is equal to null.

  • Busca elementos de tareas pendientes dentro de un cierto rango de tiempo encontrando elementos donde la propiedad progressMinutes está entre dos números.

  • Busca elementos pendientes con una cantidad determinada de progressMinutes de la lista dada.

// Find high priority to-do items by comparing the value of the ``priority``
// property value with a threshold number, above which priority can be considered high.
"priority > $0", 5
// Find long-running to-do items by seeing if the progressMinutes property is at or above a certain value.
"progressMinutes > $0", 120
// Find unassigned to-do items by finding items where the assignee property is equal to null.
"assignee == $0", null
// Find to-do items within a certain time range by finding items
// where the progressMinutes property is between two numbers.
"progressMinutes BETWEEN { $0 , $1 }", 30, 60
// Find to-do items with a certain amount of progressMinutes from the given list.
"progressMinutes IN { $0, $1, $2, $3, $4, $5 }", 10, 20, 30, 40, 50, 60

Make compound predicates using logical operators.

Operador
Descripción
AND
&&

Se evalúa como true si las expresiones de la izquierda y la derecha son true.

NOT
!

Negates the result of the given expression.

OR
||

Evaluates to true if either expression returns true.

Ejemplo

We can use the query language's logical operators to find all of Ali's completed to-do items. That is, we find all items where the assignee property value is equal to 'Ali' AND the isComplete property value is true:

"assignee == $0 AND isComplete == $1", "Ali", true

Compara valores de strings utilizando estos operadores de strings. Los comodines tipo Regex permiten una mayor flexibilidad en la búsqueda.

Nota

Puede utilizar los siguientes modificadores con los operadores de cadena:

  • [c] for case insensitivity.

    "name CONTAINS[c] $0", 'a'
Operador
Descripción
BEGINSWITH

Evaluates to true if the left-hand string expression begins with the right-hand string expression. This is similar to contains, but only matches if the right-hand string expression is found at the beginning of the left-hand string expression.

CONTAINS

Da como resultado true si la expresión de string de la derecha se encuentra en cualquier parte de la expresión de string de la izquierda.

ENDSWITH

Evaluates to true if the left-hand string expression ends with the right-hand string expression. This is similar to contains, but only matches if the left-hand string expression is found at the very end of the right-hand string expression.

LIKE

Evaluates to true if the left-hand string expression matches the right-hand string wildcard string expression. A wildcard string expression is a string that uses normal characters with two special wildcard characters:

  • The * wildcard matches zero or more of any character

  • The ? wildcard matches any character.

For example, the wildcard string "d?g" matches "dog", "dig", and "dug", but not "ding", "dg", or "a dog".

==, =

Evaluates to true if the left-hand string is lexicographically equal to the right-hand string.

!=, <>

Se evalúa como true si la cadena de la izquierda no es lexicográficamente igual a la cadena de la derecha.

Ejemplo

Se utilizan los operadores de string del motor de query para encontrar lo siguiente:

  • Projects with a name starting with the letter 'e'

  • Projects with names that contain 'ie'

"name BEGINSWITH[c] $0", 'e'
"name CONTAINS $0", 'ie'

Consulta los ObjectIds y UUID de BSON. Estos tipos de datos se utilizan a menudo como claves principales.

To query with ObjectIds, use a parameterized query. Pass the ObjectId or UUID you're querying against as the argument.

"_id == $0", oidValue

You can also put a string representation of the ObjectId you're evaluating in oid(<ObjectId String>).

"_id == oid(6001c033600510df3bbfd864)"

Para realizar consultas con UUID, coloque una representación de cadena del UUID que está evaluando en uuid(<UUID String>).

"id == uuid(d1b186e1-e9e0-4768-a1a7-c492519d47ee)"
Operador
Descripción
==, =

Devuelve true si el valor a la izquierda es igual al valor a la derecha.

!=, <>

Evaluates to true if the left-hand value is not equal to the right-hand value.

Realizar operaciones aritméticas básicas en un lado de una expresión RQL al evaluar tipos de datos numéricos.

"2 * priority > 6"
// Is equivalent to
"priority >= 2 * (2 - 1) + 2"

You can also use multiple object properties together in a mathematic operation.

"progressMinutes * priority == 90"
Operador
Descripción
*

Multiplication.

/

Division.

+

Addition.

-

Subtraction.

()

Group expressions together.

Check the type of a property using the @type operator. You can only use the type operator with mixed types and dictionaries.

Evaluate the property against a string representation of the data type name. Refer to SDK documentation on the mapping from the SDK language's data types to Realm data types.

Operador
Descripción

@type

Check if type of a property is the property name as a string. Use == and != to compare equality.

"mixedType.@type == 'string'"
"mixedType.@type == 'bool'"

Compare dictionary values using these dictionary operators.

Operador
Descripción

@values

Devuelve objetos que tienen el valor especificado en la expresión de la derecha.

@keys

Returns objects that have the key specified in the right-hand expression.

@size, @count

The number of elements in a dictionary.

Dictionary['key']

Access the value at a key of a dictionary.

ALL | ANY | NONE <property>.@type

Verifica si el diccionario contiene propiedades de cierto tipo.

También puede usar operadores de diccionario junto con operadores de comparación para filtrar objetos según sus claves y valores. Los siguientes ejemplos muestran cómo usar operadores de diccionario con operadores de comparación. Todos los ejemplos consultan una colección de objetos Realm con una propiedad de diccionario dict llamada.

Ejemplo

The following examples use various dictionary operators.

// Evaluates if there is a dictionary key with the name 'foo'
"ANY dict.@keys == $0", 'foo'
// Evaluates if there is a dictionary key with key 'foo' and value 'bar
"dict['foo'] == $0", 'bar'
// Evaluates if there is greater than one key-value pair in the dictionary
"dict.@count > $0", 1
// Evaluates if dictionary has property of type 'string'
"ANY dict.@type == 'string'"
// Evaluates if all the dictionary's values are integers
"ALL dict.@type == 'bool'"
// Evaluates if dictionary does not have any values of type int
"NONE dict.@type == 'double'"
// ANY is implied.
"dict.@type == 'string'"

query tipos de fecha en un realm.

Generally, you should use a parameterized query to pass a date data type from the SDK language you are using to a query.

"timeCompleted < $0", someDate

You can also specify dates in the following two ways:

  • As a specific date (in UTC)- YYYY-MM-DD@HH:mm:ss:nnnnnnnnnn (year-month-day@hours:minutes:seconds:nanoseconds), UTC. You can also use T instead of @ to separate the date from the time.

  • Como un tiempo en segundos desde la Unix epoch- Ts:n, donde T designa el inicio del tiempo, s es el número de segundos y n es el número de nanosegundos.

Date supports comparison operators.

Ejemplo

The following example shows how to use a parameterized query with a date object:

var date = new Date("2021-02-20@17:30:15:0");
"timeCompleted > $0", date

Apply an aggregate operator to a collection property of a Realm object. Aggregate operators traverse a collection and reduce it to a single value.

Operador
Descripción
@avg

Evaluates to the average value of a given numerical property across a collection. If any values are null, they are not counted in the result.

@count

Evalúa al número de objetos en la colección dada.

@max

Se evalúa como el valor más alto de una propiedad numérica dada en una colección. Los valores null se ignoran.

@min

Evaluates to the lowest value of a given numerical property across a collection. null values are ignored.

@sum

Evaluates to the sum of a given numerical property across a collection, excluding null values.

Ejemplo

These examples all query for projects containing to-do items that meet this criteria:

  • Proyectos con una prioridad promedio de elementos superior a 5.

  • Proyectos con un elemento cuya prioridad es menor que 5.

  • Projects with an item whose priority is greater than 5.

  • Projects with more than 5 items.

  • Projects with long-running items.

var priorityNum = 5;
"items.@avg.priority > $0", priorityNum
"items.@max.priority < $0", priorityNum
"items.@min.priority > $0", priorityNum
"items.@count > $0", 5
"items.@sum.progressMinutes > $0", 100

A collection operator lets you query list properties within a collection of objects. Collection operators filter a collection by applying a predicate to every element of a given list property of the object. If the predicate returns true, the object is included in the output collection.

Operador
Descripción

ALL

Devuelve objetos donde el predicado evalúa como true para todos los objetos de la colección.

ANY, SOME

Devuelve objetos donde el predicado evalúa a true para cualquier objeto de la colección.

NONE

Returns objects where the predicate evaluates to false for all objects in the collection.

Ejemplo

Este ejemplo utiliza operadores de colecciones para encontrar proyectos que contengan tareas pendientes que cumplan ciertos criterios:

// Projects with no complete items.
"NONE items.isComplete == $0", true
// Projects that contain a item with priority 10
"ANY items.priority == $0", 10
// Projects that only contain completed items
"ALL items.isComplete == $0", true
// Projects with at least one item assigned to either Alex or Ali
"ANY items.assignee IN { $0 , $1 }", "Alex", "Ali"
// Projects with no items assigned to either Alex or Ali
"NONE items.assignee IN { $0 , $1 }", "Alex", "Ali"

Puede utilizar operadores de comparación y operadores de colección para filtrar según listas de datos.

You can compare any type of valid list. This includes:

  • colecciones de objetos Realm, que le permiten filtrar con respecto a otros datos en el reino.

    "oid(631a072f75120729dc9223d9) IN items.id"
  • lists defined directly in the query, which let you filter against static data. You define static lists as a comma-separated list of literal values enclosed in opening ({) and closing (}) braces.

    "priority IN {0, 1, 2}"
  • objetos de lista nativos pasados ​​en una expresión parametrizada, que le permiten pasar datos de la aplicación directamente a sus consultas.

    const ids = [
    new BSON.ObjectId("631a072f75120729dc9223d9"),
    new BSON.ObjectId("631a0737c98f89f5b81cd24d"),
    new BSON.ObjectId("631a073c833a34ade21db2b2"),
    ];
    const parameterizedQuery = realm.objects("Item").filtered("id IN $0", ids);

If you do not define a collection operator, a list expression defaults to the ANY operator.

Ejemplo

Estas dos consultas de lista son equivalentes:

  • age == ANY {18, 21}

  • age == {18, 21}

Ambas consultas devuelven objetos con una propiedad de edad igual a 18 o 21. También puede hacer lo contrario y devolver objetos solo si la edad no es igual a 18 o 21:

  • age == NONE {18, 21}

The following table includes examples that illustrate how collection operators interact with lists and comparison operators:

expresión

Match?

Razón

ANY {1, 2, 3} > ALL {1, 2}

true

A value on the left (3) is greater than some value on the right (both 1 and 2)

ANY {1, 2, 3} == NONE {1, 2}

true

3 no coincide con ninguno de los dos: 1 o 2

ANY {4, 8} == ANY {5, 9, 11}

false

Ni 4 ni 8 coinciden con ningún valor en la lista de la derecha (5, 9 o 11)

ANY {1, 2, 7} <= NONE {1, 2}

true

Un valor a la izquierda (7) no es menor o igual a 1 y 2

ALL {1, 2} IN ANY {1, 2, 3}

true

Every value on the left (1 and 2) is equal to 1, 2 or 3

ALL {3, 1, 4, 3} == NONE {1, 2}

false

1 matches a value in the NONE list (1 or 2)

ALL {} in ALL {1, 2}

true

Una lista vacía coincide con todas las listas

NONE {1, 2, 3, 12} > ALL {5, 9, 11}

false

12 es mayor que todos los valores de la derecha (5, 9 y 11)

NONE {4, 8} > ALL {5, 9, 11}

true

4 y 8 son ambos menores que cierto valor a la derecha (5, 9 o 11)

NONE {0, 1} < NONE {1, 2}

true

0 and 1 are both less than none of 1 and 2

Puede utilizar RQL para consultar propiedades que tengan una anotación de búsqueda de texto completo (FTS). FTS admite búsquedas de coincidencia booleana de palabras, en lugar de búsquedas por relevancia. Para obtener información sobre cómo habilitar el FTS en una propiedad, consulte la documentación de FTS correspondiente a su SDK:

Para consultar estas propiedades, utiliza el predicado TEXT en tu query.

You can search for entire words or phrases, or limit your results with the following characters:

  • Exclude results for a word by placing the - character in front of the word.

  • Specify prefixes by placing the * character at the end of a prefix. Suffix searching is not currently supported.

En el siguiente ejemplo, consultamos la propiedad Item.name:

// Filter for items with 'write' in the name
"name TEXT $0", "write"
// Find items with 'write' but not 'tests' using '-'
"name TEXT $0", "write -tests"
// Find items starting with 'wri-' using '*'
"name TEXT $0", "wri*"

Full-Text Search (FTS) indexes support:

  • Tokens are diacritics- and case-insensitive.

  • Tokens can only consist of characters from ASCII and the Latin-1 supplement (western languages). All other characters are considered whitespace.

  • Las palabras separadas por un guion (-) se dividen en dos tokens. Por ejemplo, full-text se divide en full y text.

Puedes realizar query sobre datos geoespaciales utilizando el operador geoWithin. El operador geoWithin toma el par de latitud/longitud en la propiedad coordinates de un objeto personalizado incrustado y una forma geoespacial. El operador verifica si el punto cordinates está contenido dentro de la forma geoespacial.

The following geospatial shapes are supported for querying:

  • GeoCircle

  • GeoBox

  • GeoPolygon

Para query datos geoespaciales:

  1. Crea un objeto con una propiedad que contenga los datos geoespaciales incorporados.

  2. Define la forma geoespacial para establecer el límite de la query.

  3. Query using the geoWithin RQL operator.

In the following query, we are checking that the coordinates of the embeddeded location property are contained within the GeoCircle shape, smallCircle:

"location geoWithin $0", smallCircle

Para obtener más información sobre cómo definir formas y objetos geoespaciales con datos geoespaciales integrados, consulte la documentación geoespacial de su SDK:

A backlink is an inverse relationship link that lets you look up objects that reference another object. Backlinks use the to-one and to-many relationships defined in your object schemas but reverse the direction. Every relationship that you define in your schema implicitly has a corresponding backlink.

You can access backlinks in queries using the @links.<ObjectType>.<PropertyName> syntax, where <ObjectType> and <PropertyName> refer to a specific property on an object type that references the queried object type.

// Find items that belong to a project with a quota greater than 10 (@links)
"@links.Project.items.quota > 10"

You can also define a linkingObjects property to explicitly include the backlink in your data model. This lets you reference the backlink through an assigned property name using standard dot notation.

// Find items that belong to a project with a quota greater than 10 (LinkingObjects)
"projects.quota > 10"

El resultado de un vínculo inverso se trata como una colección y soporta operadores de colección.

// Find items where any project that references the item has a quota greater than 0
"ANY @links.Project.items.quota > 0"
// Find items where all projects that reference the item have a quota greater than 0
"ALL @links.Project.items.quota > 0"

Puede utilizar operadores agregados en la colección de vínculos de retroceso.

// Find items that are referenced by multiple projects
"projects.@count > 1"
// Find items that are not referenced by any project
"@links.Project.items.@count == 0"
// Find items that belong to a project where the average item has
// been worked on for at least 5 minutes
"@links.Project.items.items.@avg.progressMinutes > 10"

Puede consultar la cantidad de todas las relaciones que apuntan a un objeto utilizando el operador @count directamente en @links.

// Find items that are not referenced by another object of any type
"@links.@count == 0"

Iterate through list properties with another query using the SUBQUERY() predicate function.

Subqueries are useful for the following scenarios:

  • Matching each object in a list property on multiple conditions

  • Contando el número de objetos que coinciden con una subconsulta

SUBQUERY() has the following structure:

SUBQUERY(<collection>, <variableName>, <predicate>)
  • collection: The name of the property to iterate through

  • variableName:Un nombre de variable del elemento a utilizar en la subconsulta

  • predicate: El predicado de subconsulta. Utiliza la variable especificada por variableName para referirse al elemento que se está iterando actualmente.

A subquery iterates through the given collection and checks the given predicate against each object in the collection. The predicate can refer to the current iterated object with the variable name passed to SUBQUERY().

A subquery expression resolves to a list of objects. Realm only supports the @count aggregate operator on the result of a subquery. This allows you to count how many objects in the subquery input collection matched the predicate.

Puedes usar el conteo del resultado de la subconsulta como cualquier otro número en una expresión válida. En particular, puedes comparar el conteo con el número 0 para devolver todos los objetos coincidentes.

Ejemplo

The following example shows two subquery filters on a collection of projects.

// Returns projects with items that have not been completed
// by a user named Alex.
"SUBQUERY(items, $item, $item.isComplete == false AND $item.assignee == 'Alex').@count > 0"
// Returns the projects where the number of completed items is
// greater than or equal to the value of a project's `quota` property.
"SUBQUERY(items, $item, $item.isComplete == true).@count >= quota"

Sort and limit the results collection of your query using additional operators.

Operador
Descripción

SORT

Specify the name of the property to compare, and whether to sort by ascending (ASC) or descending (DESC) order. If you specify multiple SORT fields, you must specify sort order for each field. With multiple sort fields, the query sorts by the first field, and then the second.

For example, if you SORT (priority DESC, name DESC), the query returns sorted by priority, and then by name when priority value is the same.

DISTINCT

Specify a name of the property to compare. Remove duplicates for that property in the results collection. If you specify multiple DISTINCT fields, the query removes duplicates by the first field, and then the second. For example, if you DISTINCT (name, assignee), the query only removes duplicates where the values of both properties are the same.

LIMIT

Limita la colección de resultados al número especificado.

Ejemplo

Use the query engine's sort, distinct, and limit operators to find to-do items where the assignee is Ali:

  • Sorted by priority in descending order

  • Enforcing uniqueness by name

  • Limitar los resultados a 5 elementos

"assignee == 'Ali' SORT(priority DESC) DISTINCT(name) LIMIT(5)"

Adding an indexed queryable field to your App can improve performance for simple queries on data that is strongly partitioned. For example, an app where queries strongly map data to a device, store, or user, such as user_id == $0, “641374b03725038381d2e1fb”, is a good candidate for an indexed queryable field. However, an indexed queryable field has specific requirements for use in a query subscription:

  • The indexed queryable field must be used in every subscription query. It cannot be missing from the query.

  • The indexed queryable field must use an == or IN comparison against a constant at least once in the subscription query. (El campo consultable debe utilizar una comparación o contra una constante al menos una vez en la consulta de suscripción.) For example, user_id == $0, "641374b03725038381d2e1fb" or store_id IN $0, {1,2,3}. (Por ejemplo, o .)

Opcionalmente, puedes incluir una comparación de AND siempre que el campo indexado consultable se compare directamente con una constante usando == o IN al menos una vez. Por ejemplo, store_id IN {1,2,3} AND region=="Northeast" o store_id == 1 AND (active_promotions < 5 OR num_employees < 10).

Invalid Flexible Sync queries on an indexed queryable field include queries where:

  • The indexed queryable field does not use AND with the rest of the query. For example store_id IN {1,2,3} OR region=="Northeast" is invalid because it uses OR instead of AND. Similarly, store_id == 1 AND active_promotions < 5 OR num_employees < 10 is invalid because the AND only applies to the term next to it, not the entire query.

  • El campo consultable indexado no se utiliza en un operador de igualdad. Por ejemplo, store_id > 2 AND region=="Northeast" no es válido porque solo utiliza el operador > con el campo consultable indexado y no tiene una comparación de igualdad.

  • The query is missing the indexed queryable field entirely. For example, region=="Northeast or truepredicate are invalid because they do not contain the indexed queryable field.

Flexible Sync has some limitations when using RQL operators. When you write the query subscription that determines which data to sync, the server does not support these query operators. However, you can still use the full range of RQL features to query the synced data set in the client application.

Tipo de operador
Operadores no compatibles

Aggregate Operators

@avg, @count, @max, @min, @sum

Query Suffixes

DISTINCT, SORT, LIMIT

Las queries que no distinguen entre mayúsculas y minúsculas ([c]) no pueden usar índices de manera eficaz. Como resultado, no se recomiendan las queries que no distinguen entre mayúsculas y minúsculas, ya que podrían provocar problemas de rendimiento.

Flexible Sync only supports @count for array fields.

Flexible Sync admite la consulta de listas usando el operador IN.

Puede consultar una lista de constantes para ver si contiene el valor de un campo consultable:

// Query a constant list for a queryable field value
"priority IN { 1, 2, 3 }"

If a queryable field has an array value, you can query to see if it contains a constant value:

// Query an array-valued queryable field for a constant value
"'comedy' IN genres"

Advertencia

You cannot compare two lists with each other in a Flexible Sync query. Note that this is valid Realm Query Language syntax outside of Flexible Sync queries.

// Invalid Flexible Sync query. Do not do this!
"{'comedy', 'horror', 'suspense'} IN genres"
// Another invalid Flexible Sync query. Do not do this!
"ANY {'comedy', 'horror', 'suspense'} != ANY genres"

Flexible Sync does not support querying on properties in Embedded Objects or links. For example, obj1.field == "foo".

The size limit for any given query subscription in your subscription set is 256 kB. Exceeding this limit results in a LimitsExceeded Error.

Volver

Modify Schema