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
/ /
Read & Write Data

Borrar objetos Realm - Kotlin SDK

This page describes how to delete objects from a local or synced realm using the Kotlin SDK.

Puedes elegir borrar un solo objeto, varios objetos o todos los objetos del realm. Después de borrar un objeto, ya no se puede acceder ni modificar. Si intentas usar un objeto eliminado, Realm arroja un error.

Deleting objects from a realm does not delete the realm file or affect the realm schema. It only deletes the object instance from the realm. If you want to delete the realm file itself, refer to Delete a Realm - Kotlin SDK.

Nota

Write to a Synced Realm

The syntax to delete an object from a realm is the same for a local or a synced realm. However, there are additional considerations that determine whether the delete operation in a synced realm is successful. For more information, refer to Write Data to a Synced Realm - Kotlin SDK.

Todas las operaciones que modifican un dominio, incluidas las de eliminación, deben realizarse dentro de una transacción de escritura. Las transacciones de escritura se pasan al dominio. Método write() o writeBlocking(). Con esta devolución de llamada, puede acceder a una instancia de MutableRealm y luego eliminar objetos dentro del dominio. Para obtener más información sobre las transacciones de escritura y cómo las gestiona Realm, consulte Transacciones de escritura.

Solo puedes borrar objetos activos, que solo son accesibles dentro de una transacción de escritura. Puede convertir un objeto congelado en un objeto activo en una transacción con mutableRealm.findLatest().

Ejemplo

Convert Frozen Object Before Deleting

val frozenFrog = realm.query<Frog>("name == $0", "Kermit").find().firstOrNull()
// Open a write transaction
realm.writeBlocking {
// Get the live frog object with findLatest(), then delete it
if (frozenFrog != null) {
findLatest(frozenFrog)
?.also { delete(it) }
}
}

Al eliminar un objeto que tiene una propiedad de relación con otro objeto, Realm no elimina automáticamente la instancia del objeto relacionado. En su lugar, solo elimina la referencia al otro objeto. El objeto referenciado permanece en el dominio, pero ya no se puede consultar a través de la propiedad principal.

La única excepción es si el objeto relacionado está incrustado. Cuando se elimina un objeto que tiene una relación con un EmbeddedRealmObjectRealm elimina automáticamente el objeto incrustado mediante una eliminación en cascada. Para obtener más información, consulte la sección "Eliminar un objeto incrustado" en esta página.

Si desea eliminar objetos relacionados al eliminar un objeto principal, le recomendamos realizar una eliminación encadenada. Esta eliminación consiste en eliminar manualmente los objetos dependientes iterando sobre las dependencias y eliminándolos antes de eliminar el objeto principal. Para obtener más información sobre las eliminaciones encadenadas, consulte la sección "Eliminar un objeto y sus objetos relacionados" en esta página.

Si no borras tú mismo los objetos relacionados, quedarán huérfanos en tu realm. Si esto es un problema o no depende de las necesidades de tu aplicación.

To delete specific objects from a realm:

  1. Abra una transacción de escritura con realm.write() o realm.writeBlocking().

  2. Obtenga los objetos activos consultando el ámbito mutable de la transacción para los objetos que desea eliminar usando query():

    1. Especifica el tipo de objeto Realm como un parámetro de tipo pasado a query().

    2. (Optional) Filter the set of returned objects by specifying a query. If you don't include a query filter, you return all objects of the specified type. For more information on querying with the Kotlin SDK, refer to Read Realm Objects - Kotlin SDK.

    Importante

    Objects Must Be Live

    Solo se pueden eliminar objetos activos. Si la consulta se produce fuera de la transacción de escritura, debe convertir los objetos congelados en activos en la transacción con mutableRealm.findLatest().

  3. Pass the set of RealmResults returned by the query to mutableRealm.delete().

  4. Los objetos especificados se eliminan del realm y ya no pueden ser accedidos ni modificados. Si intentas usar un objeto eliminado, Realm arroja un error.

    If any deleted objects had a relationship with another object, Realm only deletes the reference to the other object. The referenced object remains in the realm, but it can no longer be queried through the deleted parent property. Refer to the Delete an Object and Its Related Objects section for more information.

Tip

Puedes comprobar si un objeto sigue siendo válido llamando a isValid(). Los objetos eliminados false devuelven.

To delete a single RealmObject object, query for the object type using a filter that returns the specific object that you want to delete.

Tip

Use Unique Identifying Information

We recommend filtering with unique identifying information such as a primary key value to ensure your query returns the correct object.

In the following example, we query for a Frog object with a specific primary key, and then pass the returned object to mutableRealm.delete() to delete it from the realm:

// Open a write transaction
realm.write {
// Query the Frog type and filter by primary key value
val frogToDelete: Frog = query<Frog>("_id == $0", PRIMARY_KEY_VALUE).find().first()
// Pass the query results to delete()
delete(frogToDelete)
}

Para borrar varios objetos al mismo tiempo, pase el tipo de objeto Realm a query() y especifique una query que devuelva todos los objetos que desea borrar.

In the following example, we query for the first three Frog objects whose species is "bullfrog", and then pass the results to mutableRealm.delete() to delete them from the realm:

// Open a write transaction
realm.write {
// Query by species and limit to 3 results
val bullfrogsToDelete: RealmResults<Frog> = query<Frog>("species == 'bullfrog' LIMIT(3)").find()
// Pass the query results to delete()
delete(bullfrogsToDelete)
}

To delete all objects of a specific type from a realm at the same time, pass the object type to query() and leave the query filter empty to return all objects of that type.

In the following example, we query for all Frog objects, and then pass the results to mutableRealm.delete() to delete them all from the realm:

// Open a write transaction
realm.write {
// Query Frog type with no filter to return all frog objects
val frogsLeftInTheRealm = query<Frog>().find()
// Pass the query results to delete()
delete(frogsLeftInTheRealm)
}

The Kotlin SDK lets you delete all managed objects of all types, which is useful for quickly clearing out your realm while prototyping. This does not affect the realm schema or any objects that are not managed by the realm.

Para eliminar todos los objetos del realm al mismo tiempo, llama a mutableRealm.deleteAll(). Esto borra todos los objetos de todos los tipos.

En el siguiente ejemplo, eliminamos todos los objetos del realm con deleteAll():

// Open a write transaction
realm.write {
// Delete all objects from the realm
deleteAll()
}

Tip

Use deleteAll() in Development

The deleteAll() method is useful for quickly clearing out your realm during development. For example, instead of writing a migration to update objects to a new schema, it may be faster to delete all, and then re-generate the objects with the app itself.

Borrar un objeto primario no borra automáticamente ningún objeto relacionado a menos que el objeto relacionado esté embebido. En su lugar, Realm solo borra la referencia al objeto relacionado.

In the following example, we have a Frog object with a list of Pond objects. After we delete the Frog object, we confirm that all Pond objects still remain in the realm:

// Open a write transaction
realm.write {
// Query for the parent frog object with ponds
val parentObject = query<Frog>("_id == $0", PRIMARY_KEY_VALUE).find().first()
assertEquals(2, parentObject.favoritePonds.size)
// Delete the frog and all references to ponds
delete(parentObject)
// Confirm pond objects are still in the realm
val ponds = query<Pond>().find()
assertEquals(2, ponds.size)
}

To delete related objects when you delete a parent object, you must manually delete the related objects yourself. We recommend chaining deletes: first query for the parent object that you want to delete, then iterate through the parent object's relationships and delete each related object. Finally, delete the parent object itself.

In the following example, we query for a Frog object named "Kermit", then iterate through the object's favoritePonds property and delete each Pond object. Then, we delete the Frog object itself:

realm.write {
// Query for the parent frog object with ponds
val frog = query<Frog>("name == $0", "Kermit").find().first()
val ponds = frog.favoritePonds
// Iterate over the list and delete each pond object
if (ponds.isNotEmpty()) {
ponds.forEach { pond ->
delete(pond)
}
}
// Delete the parent frog object
val frogToDelete = findLatest(frog)
if (frogToDelete != null) {
delete(frogToDelete)
}
}

Advertencia

Realm Uses Cascading Deletes for Embedded Objects

When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object. If you want the referenced objects to persist after the deletion of the parent object, use a regular Realm object with a to-one relationship instead.

Puede eliminar un objeto incrustado a través del objeto principal en una eliminación en cascada o eliminando el objeto incrustado directamente.

  • To delete the embedded object through the parent object, fetch and delete the parent object. Realm automatically deletes all of its embedded objects from the realm.

  • To delete an embedded object instance directly:

    • Fetch and delete a specific embedded object.

    • Clear the parent's reference to the embedded object, which also deletes the embedded object instance.

En el siguiente ejemplo, tenemos un objeto Business con una lista de objetos EmbeddedAddress incrustados. Hacemos una query y borramos el objeto Business, lo que borra automáticamente todos sus objetos EmbeddedAddress integrados:

// Delete the parent object
realm.write {
val businessToDelete = query<Business>("name == $0", "Big Frog Corp.").find().first()
// Delete the parent object (deletes all embedded objects)
delete(businessToDelete)
}

En el siguiente ejemplo, tenemos objetos Contact con objetos EmbeddedAddress incrustados. Eliminamos un objeto EmbeddedAddress directamente y otro a través del objeto principal:

// Delete an embedded object directly
realm.write {
val addressToDelete = query<EmbeddedAddress>("street == $0", "456 Lily Pad Ln").find().first()
// Delete the embedded object (nullifies the parent property)
delete(addressToDelete)
}
// Delete an embedded object through the parent
realm.write {
val propertyToClear = query<Contact>("name == $0", "Kermit").find().first()
// Clear the parent property (deletes the embedded object instance)
propertyToClear.address = null
}

Tip

Get Embedded Object's Parent

You can get the unique parent of an embedded object using parent().

Las instancias de colecciones de Realm que contienen objetos solo almacenan referencias a esos objetos. Puedes remover uno o más objetos referenciados de una colección sin borrar los objetos en sí. Los objetos que eliminas de una colección permanecen en el 'realm' hasta que los eliminas manualmente. Alternativamente, borrar un objeto Realm de un realm también borra ese objeto de cualquier instancia de colección que lo contenga.

You can remove one or more elements in a single transaction from a RealmList:

  • To remove one element from the list, pass the element to list.remove().

  • To remove one element at a specified index in the list, pass the index to list.removeAt().

  • To remove multiple elements from the list, pass the elements to list.removeAll().

También puedes eliminar todos los elementos de la lista a la vez llamando a list.clear().

In the following example, we have a Forest object with a list of Pond objects. We remove the list elements in a series of operations until the list is empty:

// Open a write transaction
realm.write {
// Query for the parent forest object
val forest = query<Forest>("name == $0", "Hundred Acre Wood").find().first()
val forestPonds = forest.nearbyPonds
assertEquals(5, forestPonds.size)
// Remove the first pond in the list
val removeFirstPond = forestPonds.first()
forestPonds.remove(removeFirstPond)
assertEquals(4, forestPonds.size)
// Remove the pond at index 2 in the list
forestPonds.removeAt(2)
assertEquals(3, forestPonds.size)
// Remove the remaining three ponds in the list
forestPonds.removeAll(forestPonds)
assertEquals(0, forestPonds.size)
}

In the following example, we have a Forest object with a list of Pond objects. We remove all list elements with the list.clear() method:

// Open a write transaction
realm.write {
val forest = query<Forest>("name == $0", "Hundred Acre Wood").find().first()
val forestPonds = forest.nearbyPonds
assertEquals(5, forestPonds.size)
// Clear all ponds from the list
forestPonds.clear()
assertEquals(0, forestPonds.size)
}

Puedes remover uno o más elementos en una sola transacción desde un RealmSet:

  • Para eliminar un elemento del conjunto, pase el elemento que desea eliminar a set.remove().

  • Para eliminar varios elementos del conjunto, pase los elementos que desea eliminar a set.removeAll().

También puedes eliminar todos los elementos del conjunto a la vez llamando set.clear().

In the following example, we have a Frog object with a set of Snack objects. We remove the set elements in a series of operations until the set is empty:

// Open a write transaction
realm.write {
// Query for the parent frog object
val myFrog = query<RealmSet_Frog>("name == $0", "Kermit").find().first()
val snackSet = myFrog.favoriteSnacks
assertEquals(3, snackSet.size)
// Remove one snack from the set
snackSet.remove(snackSet.first { it.name == "Flies" })
assertEquals(2, snackSet.size)
// Remove the remaining two snacks from the set
val allSnacks = findLatest(myFrog)!!.favoriteSnacks
snackSet.removeAll(allSnacks)
assertEquals(0, snackSet.size)
}

En el siguiente ejemplo, tenemos un objeto Frog con un conjunto de objetos Snack. Removemos todos los elementos del conjunto con el método set.clear():

realm.write {
val myFrog = realm.query<RealmSet_Frog>("name == $0", "Kermit").find().first()
val snackSet = findLatest(myFrog)!!.favoriteSnacks
assertEquals(3, snackSet.size)
// Clear all snacks from the set
snackSet.clear()
assertEquals(0, snackSet.size)
}

You can remove RealmDictionary entries in a few ways:

  • Para eliminar el valor pero conservar la clave, establezca la clave en null (el valor del diccionario debe ser nulo)

  • Para eliminar la clave y el valor, pasa la clave a remover()

You can also remove all keys and values by calling clear().

In the following example, we have a Frog object with a dictionary of String values. We remove the dictionary elements in a series of operations until the dictionary is empty:

// Find frogs who have forests with favorite ponds
val thisFrog = realm.query<Frog>("favoritePondsByForest.@count > 1").find().first()
// Set an optional value for a key to null if the key exists
if (thisFrog.favoritePondsByForest.containsKey("Hundred Acre Wood")) {
realm.write {
val mutableFrog = findLatest(thisFrog)
if (mutableFrog != null) {
mutableFrog.favoritePondsByForest["Hundred Acre Wood"] = null
}
}
}
realm.write {
// Remove a key and its value
findLatest(thisFrog)?.favoritePondsByForest?.remove("Lothlorien")
// Remove all keys and values
findLatest(thisFrog)?.favoritePondsByForest?.clear()
assertTrue(thisFrogUpdated.favoritePondsByForest.isEmpty())
}

Although RealmAny instances cannot store null values, you can delete a RealmAny property value by assigning null directly to the property. For more information on the RealmAny data type, refer to RealmAny (Mixed).

In the following example, we have a Frog object with a list of RealmAny properties, and we clear the first RealmAny property value:

realm.write {
val frog = query<Frog>().find().first()
frog.favoriteThings[0] = null
}

Volver

Update