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 - C++ SDK

CRUD - Lectura - SDK C++

You can read back the data that you have stored in Realm by finding, filtering, and sorting objects.

A read from a realm generally consists of the following steps:

  • Get all objects of a certain type from the realm.

  • Opcionalmente, puedes filtrar los resultados.

Operaciones query devuelven una colección de resultados. Estas colecciones son activas, lo que significa que siempre contienen los resultados más recientes de la query correspondiente.

Diseñe los patrones de acceso a datos de su aplicación en torno a estas tres características de lectura clave para leer los datos de la manera más eficiente posible.

Results to a query are not copies of your data. Modifying the results of a query modifies the data on disk directly. This memory mapping also means that results are live: that is, they always reflect the current state on disk.

Realm only runs a query when you actually request the results of that query. This lazy evaluation enables you to write highly performant code for handling large data sets and complex queries. You can chain several filter operations without requiring extra work to process the intermediate state.

One benefit of Realm's object model is that Realm automatically retains all of an object's relationships as direct references. This enables you to traverse your graph of relationships directly through the results of a query.

Una referencia directa, o puntero, te permite acceder directamente a las propiedades de un objeto relacionado a través de la referencia.

Otras bases de datos suelen copiar objetos del almacenamiento de la base de datos a la memoria de la aplicación cuando necesitas trabajar directamente con ellos. Debido a que los objetos de la aplicación contienen referencias directas, tienes la siguiente opción: copiar el objeto al que se hace referencia en cada referencia directa fuera de la base de datos en caso de que sea necesario, o simplemente copiar la clave externa de cada objeto y hacer query para el objeto con esa clave si se accede a él. Si eliges copiar objetos referenciados a la memoria de la aplicación, puedes usar muchos recursos para objetos a los que nunca se accede, pero si elige solo copiar la clave externa, las búsquedas de objetos referenciados pueden causar que su aplicación se vuelva lenta.

Realm bypasses all of this using zero-copy live objects. Realm object accessors point directly into database storage using memory mapping, so there is no distinction between the objects in Realm and the results of your query in application memory. Because of this, you can traverse direct references across an entire realm from any query result.

As a result of lazy evaluation, you do not need any special mechanism to limit query results with Realm. For example, if your query matches thousands of objects, but you only want to load the first ten, simply access only the first ten elements of the results collection.

Thanks to lazy evaluation, the common task of pagination becomes quite simple. For example, suppose you have a results collection associated with a query that matches thousands of objects in your realm. You display one hundred objects per page. To advance to any page, simply access the elements of the results collection starting at the index that corresponds to the target page.

Para consultar objetos de un tipo determinado en un reino, pase el tipo de objeto YourClassName a la función miembrorealm::query.<T>

This returns a Results object representing all objects of the given type in the realm.

auto managedBusinesses = realm.objects<realm::Business>();

A filter selects a subset of results based on the value(s) of one or more object properties. Realm provides a full-featured query engine that you can use to define filters.

auto businessesNamedMongoDB = managedBusinesses.where(
[](auto &business) { return business.name == "MongoDB"; });

Actualmente, el C++ SDK de Realm es compatible con los siguientes operadores del query:

  • Equality (==, !=)

  • Greater than/less than (>, >=, <, <=)

  • Compound queries (||, &&)

Realm Results exposes member functions to work with results. You may want to check the size of a results set, or access the object at a specific index.

auto managedBusinesses = realm.objects<realm::Business>();
auto businessesNamedMongoDB = managedBusinesses.where(
[](auto &business) { return business.name == "MongoDB"; });
CHECK(businessesNamedMongoDB.size() >= 1);
auto mongoDB = businessesNamedMongoDB[0];

Además, puedes iterar por los resultados, u observar un conjunto de resultados por cambios.

Puede iterar y verificar los valores de una propiedad de mapa de reino como lo haría con un mapa C++ estándar:

auto employees = realm.objects<realm::Employee>();
auto employeesNamedTommy = employees.where(
[](auto &employee) { return employee.firstName == "Tommy"; });
auto tommy = employeesNamedTommy[0];
// You can get an iterator for an element matching a key using `find()`
auto tuesdayIterator = tommy.locationByDay.find("Tuesday");
// You can access values for keys like any other map type
auto mondayLocation = tommy.locationByDay["Monday"];

You can iterate, check the size of a set, and find values in a set property:

auto repositories = realm.objects<realm::Repository>();
auto repositoriesNamedDocsRealm = repositories.where([](auto &repository) {
return repository.ownerAndName == "mongodb/docs-realm";
});
auto docsRealm = repositoriesNamedDocsRealm[0];
// You can check the size of the set
auto numberOfPullRequests = docsRealm.openPullRequestNumbers.size();
// Find an element in the set whose value is 3064
auto it = managedDocsRealm.openPullRequestNumbers.find(3064);
// Get a copy of the set that exists independent of the managed set
auto openRealmPullRequests = docsRealm.openPullRequestNumbers.detach();

A sort operation allows you to configure the order in which Realm returns list objects and query results. You can sort based on one or more properties of the objects in the list or results collection. Realm only guarantees a consistent order if you explicitly sort.

A diferencia de usar std::sort, la implementación de sort de Realm conserva la carga diferida de objetos. No extrae todo el conjunto de resultados ni los objetos de lista a memoria, sino que solo los carga cuando se accede a ellos.

Para ordenar, llame a la .sort() función en una lista o conjunto de resultados con uno o más sort_descriptors.

A sort_descriptor includes:

  • The desired key path to sort by, as a string.

  • Un bool para especificar el orden de clasificación, donde ``true`` es ascendente y false es descendente.

In this example, we sort a results set on priority in descending order.

auto items = realm.objects<realm::Item>();
// Sort with `false` returns objects in descending order.
auto itemsSorted = items.sort("priority", false);

You can also sort a list or results set by multiple sort descriptors. In this example, we sort a list property on assignee in ascending order, and then on priority in descending order.

auto sortedListProperty =
specificProject.items.sort({{"assignee", true}, {"priority", false}});

Volver

Crear