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
/ /
CRUD

Query Data - Node.js SDK

To filter data in your Realms, construct queries with Realm Query Language. Queries always reflect the latest state of an object and emit notifications that can update your app whenever data changes.

Para obtener más información sobre la sintaxis, el uso y las limitaciones, consulta la Referencia del lenguaje de consultas de Realm.

A results collection represents all objects in a realm that match a query operation. In general you can work with a collection like a regular JavaScript array but collections don't actually hold matching Realm objects in memory. Instead they reference the matched objects, which themselves map directly to data in the realm file.

Nota

Paginación y Límites

Some queries only need to access a subset of all objects that match the query. Realm's lazy-loaded collections only fetch objects when you actually access them, so you do not need any special mechanism to limit query results.

For example, if you only want to find 10 matching objects at a time (such as in a paged product catalog) you can just access ten elements of the results collection. To advance to the next page, access the next ten elements of the results collection starting at the index immediately following the last element of the previous page.

Los ejemplos de esta página utilizan un conjunto de datos simple para una aplicación de lista de tareas. Los dos tipos de objetos Realm son Project y Task. Un Task tiene un nombre, el nombre del asignado y una marca de finalización. También hay un número arbitrario para la prioridad (cuanto más alto, más importante) y un recuento de minutos dedicados a trabajar en él. Un Project tiene cero o más Tasks.

Vea el esquema de estas dos clases, Project y Task:

const TaskSchema = {
name: "Task",
properties: {
name: "string",
isComplete: "bool",
priority: "int",
progressMinutes: "int",
assignee: "string?"
}
};
const ProjectSchema = {
name: "Project",
properties: {
name: "string",
tasks: "Task[]"
}
};

Para filtrar datos, pase una consulta realizada con Realm Query Language a Reino.Resultados.filtrados().

const items = realm.objects("Item");
// Gets all items where the 'priority' property is 7 or more.
const importantItems = items.filtered("priority >= $0", 7);

Puedes usar el Realm Query Language (RQL) para query propiedades que tengan un índice de búsqueda de texto completo (FTS). Para consultar una propiedad indexada por FTS, utiliza el predicado TEXT en tu query filtrada.

Exclude results for a word by placing the hyphen (-) character in front of the word. For example, a search for swan -lake would include all search results for swan excluding those with lake.

In the following example, we query on the Book.name field using the following Book object model:

class Book extends Realm.Object<Book> {
name!: string;
price?: number;
static schema: ObjectSchema = {
name: "Book",
properties: {
name: { type: "string", indexed: "full-text" },
price: "int?",
},
};
}
// Retrieve book objects from realm
const books = realm.objects(Book);
// Filter for books with 'hunger' in the name
const booksWithHunger = books.filtered("name TEXT $0", "hunger");
// Filter for books with 'swan' but not 'lake' in the name
const booksWithSwanWithoutLake = books.filtered("name TEXT $0", "swan -lake");

Full-Text Search (FTS) indexes support:

  • Boolean match word searches, not searches for relevance.

  • Tokens are diacritics- and case-insensitive.

  • Words split by a hyphen (-), like full-text, are split into two tokens.

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

Existen varios tipos de operadores disponibles para filtrar una colección de Realm. Los filtros funcionan evaluando una expresión de operador para cada objeto de la colección que se filtra. Si la expresión se resuelve true como, Realm Database incluye el objeto en la colección de resultados.

An expression consists of one of the following:

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

  • An operator and up to two argument expression(s).

  • A literal string, number, or date.

The most straightforward operation in a search is to compare values. Realm Query Language has standard comparison operators like ==, >, >=, in, <, <=, and !=.

Para obtener documentación completa sobre los operadores de comparación, consulta la referencia de operadores de comparación del Realm Query Language.

The following example uses the query engine's comparison operators to:

  • Encuentre tareas de alta prioridad comparando el valor de la propiedad priority con un número umbral, por encima del cual la prioridad puede considerarse alta.

  • Find just-started or short-running tasks by seeing if the progressMinutes property falls within a certain range.

  • Find unassigned tasks by finding tasks where the assignee property is equal to null.

  • Find tasks assigned to specific teammates Ali or Jamie by seeing if the assignee property is in a list of names.

const highPriorityTasks = tasks.filtered("priority > $0", 5);
const unassignedTasks = tasks.filtered("assignee == $0", null);
const lowProgressTasks = tasks.filtered("$0 <= progressMinutes && progressMinutes < $1", 1, 10);
const aliTasks = tasks.filtered("assignee == $0", "Ali");
console.log(
`Number of high priority tasks: ${highPriorityTasks.length}`,
`Number of unassigned tasks: ${unassignedTasks.length}`,
`Number of just-started or short-running tasks: ${lowProgressTasks.length}`,
`Number of tasks for Ali: ${aliTasks.length}`
);

Create compound predicates using logical operators. Realm Query Language has standard logical operators like AND, OR, and NOT.

For complete documentation on logical operators, refer to the Realm Query Language logical operator reference.

El siguiente ejemplo utiliza los operadores lógicos de Realm Query Language para encontrar todas las tareas completadas de Ali. Encontramos todas las tareas donde el valor de la propiedad assignee es igual a 'Ali' Y el valor de la propiedad isComplete es true.

console.log(
"Number of Ali's complete tasks: " +
tasks.filtered("assignee == $0 && isComplete == $1", "Ali", true).length
);

You can compare string values using string operators like ==, beginsWith, contains, and endsWith. You can also use the LIKE operator to search with regex-like wildcards.

For complete documentation on string operators, refer to the Realm Query Language string operator reference.

El siguiente ejemplo utiliza los operadores de cadena de Realm Query Language para encontrar proyectos con un nombre que comience con la letra "e" y proyectos con nombres que contengan "ie".

// Use [c] for case-insensitivity.
console.log(
"Projects that start with 'e': " +
projects.filtered("name BEGINSWITH[c] $0", 'e').length
);
console.log(
"Projects that contain 'ie': " +
projects.filtered("name CONTAINS $0", 'ie').length
);

Recorrer una colección y reducirla a un único valor con un operador agregado.

For complete documentation on aggregate operators, refer to the Realm Query Language aggregate operator reference.

The following examples uses aggregate operators to show different facets of the data:

  • @avg para mostrar proyectos con prioridad promedio de tareas superior a 5.

  • @sum para mostrar proyectos de larga duración.

console.log(
"Number of projects with average tasks priority above 5: " +
projects.filtered("tasks.@avg.priority > $0", 5).length
);
console.log(
"Number of long-running projects: " +
projects.filtered("tasks.@sum.progressMinutes > $0", 120).length
);

Un operador de colección utiliza reglas para determinar si se debe pasar cada objeto de colección de entrada a la colección de salida aplicando un predicado determinado a cada elemento de una propiedad de lista determinada del objeto.

Para la documentación completa sobre operadores de recolección, consulta la referencia de operadores de colección de Realm Query Language.

The following examples uses Realm Query Language's collection operators to find:

  • ALL for projects with no complete tasks.

  • ANY para proyectos con tareas de máxima prioridad.

console.log(
"Number of projects with no complete tasks: " +
projects.filtered("ALL tasks.isComplete == $0", false).length
);
console.log(
"Number of projects with any top priority tasks: " +
projects.filtered("ANY tasks.priority == $0", 10).length
);
  • Use Realm.Results.filtered to filter data in your realm using Realm Query Language.

  • For a detailed explanation of Realm Query Language, refer to the Realm Query Language reference.

  • There are several categories of operators available to filter results: - comparison - logical - string - aggregate - set

Volver

Borrar

En esta página