Delete Objects and Property Values
On this page
- Delete Operations
- Related Objects and References
- Delete Objects
- Delete a Single Object
- Delete Multiple Objects
- Delete All Objects of a Type
- Delete All Objects in the Database
- Delete Related Objects
- Delete an Object and Its Related Objects
- Delete an Embedded Object
- Delete Property Values
- Delete an Inverse Relationship
- Delete Mixed Property Values
- Remove Elements from Collections
- Remove Elements from a List
- Remove Elements from a Set
- Remove Dictionary Keys/Values
This page describes how to delete objects from a non-synced or synced database using Atlas Device SDK.
You can choose to delete a single object, multiple objects, or all objects from the database. After you delete an object, you can no longer access or modify it. If you try to use a deleted object, the SDK throws an error.
Deleting objects from a database does not delete the database file or affect the database schema. It only deletes the object instance from the database. If you want to delete the database file itself, refer to Delete a Database File. If you want to remove objects or properties from the database schema, refer to Change an Object Model.
Note
Write to a Synced Database
The syntax to delete an object from the database is the same for a non-synced or a synced database. However, there are additional considerations that determine whether the delete operation in a synced database is successful. For more information, refer to Write Data to a Synced Database.
Delete Operations
Delete operations must be performed inside of a write transaction. For more information on write transactions and how the SDK handles them, refer to Write Transactions.
To delete an object from the database, pass the object to the db.remove() function inside of a write transaction.
You can only delete live objects. If you are working with a frozen object, such as when passing an object across threads, you must query for the frozen object on the new thread in order to delete it.
Similarly, if you're passing a ThreadSafeReference for an object you want to delete, you must resolve the reference and then delete the resovled object.
For more information about working with objects across threads, refer to Threading.
You can only delete live objects. If you are working with a frozen object, such as when passing an object across isolates, you must query for the frozen object in order to delete it.
You can only delete live objects. If you are working with a frozen object, such as when passing an object across threads, you must query for the frozen object on the new thread in order to delete it.
Write transactions are passed to the database's write() or writeBlocking() method. Within this callback, you can access a MutableRealm instance and then delete objects within the database.
You can only delete live objects, which are only accessible inside of a write transaction. You can convert a frozen object to a live object in a transaction with mutableRealm.findLatest().
You can only delete live objects. If you are working with a frozen object, such as when passing an object across threads, you must query for the frozen object on the new thread in order to delete it.
You can only delete live objects. If you are working with a frozen object, such as when passing an object across threads, you can convert the frozen object to a live object by calling the thaw method. You can thaw objects, collections, or database instances.
Similarly, if you're passing an RLMThreadSafeReference for an object you want to delete, you must resolve the reference and then delete the resovled object.
For more information about working with objects across threads, refer to Threading.
You can only delete live objects. If you are working with a frozen object, such as when passing an object across threads, you can convert the frozen object to a live object by calling the thaw() method. You can thaw objects, collections, or database instances.
Similarly, if you're passing a ThreadSafeReference for an object you want to delete, you must resolve the reference within the write transaction and then delete the resovled object.
For more information about working with objects across threads, refer to Threading.
realm.write([&] { realm.remove(managedDog); });
realm.Write(() => { // Remove the instance from the realm. realm.Remove(dog); // Discard the reference. dog = null; });
realm.write(() { realm.delete(obiWan); });
realm.executeTransaction(r -> { // Get a turtle named "Tony". Turtle tony = r.where(Turtle.class).equalTo("name", "Tony").findFirst(); tony.deleteFromRealm(); // discard the reference tony = null; });
realm.write(() => { // Delete the dog from the realm. realm.delete(dog); // Discard the reference. dog = null; });
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) } } }
realm.executeTransaction { r: Realm -> // Get a turtle named "Tony". var tony = r.where(Turtle::class.java) .equalTo("name", "Tony") .findFirst() tony!!.deleteFromRealm() // discard the reference tony = null }
[realm transactionWithBlock:^() { // Delete the instance from the realm. [realm deleteObject:dog]; }];
// Previously, we've added a dog object to the realm. let dog = Dog(value: ["name": "Max", "age": 5]) let realm = try! Realm() try! realm.write { realm.add(dog) } // Delete the instance from the realm. try! realm.write { realm.delete(dog) }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Related Objects and References
When you delete an object that has a relationship property with another object, the SDK does not automatically delete the instance of the related object. Instead, the SDK only deletes the reference to the other object. The referenced object instance remains in the database, but it can no longer be queried through the relationship property.
Embedded objects are handled differently. When you delete an object that contains an embedded object, the SDK automatically deletes the embedded object in a cascading delete. This is because embedded objects do not have a lifecycle outside of their parent object. For more information, refer to the Delete an Embedded Object section on this page.
Chaining Deletes with Related SDK Objects
If you want to delete any related objects when you delete a parent object, we recommend performing a chaining delete. A chaining delete consists of manually deleting dependent objects by iterating through the dependencies and deleting them before deleting the parent object. For more information on chaining deletes, refer to the Delete Related Objects section on this page.
If you do not delete the related objects yourself, they remain in your database. Whether or not this is a problem depends on your application's needs.
Delete Objects
Open a write transaction with db.write().
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object or thread-safe reference, you must
thaw()
the object orresolve()
the thread-safe reference before deleting the object. For more details, refer to Threading.Call the
remove()
method with the object you want to delete as an argument.The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Open a write transaction with Realm.Write or Realm.WriteAsync.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object or thread-safe reference, you must query for the live object or resolve the thread-safe reference before deleting the object. For more details, refer to Threading.
Call the Remove method with the object you want to delete as an argument.
The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isValid.
Deleted objects return false
.
Open a write transaction with realm.write or realm.writeAsync.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object, you must query for the live object before deleting the object.
Call the delete method with the object you want to delete as an argument.
The specified object is deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by checking the
object's isValid
property. Deleted objects return false
.
Open a write transaction with one of the relevant APIs.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object, you query for the live version of the object on the local thread before deleting the object. For more details, refer to Threading.
Call the
delete()
method with the object you want to delete as an argument.The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isValid().
Deleted objects return false
.
Open a write transaction with realm.write.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Call the delete method with the object you want to delete as an argument.
The specified object is deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isValid
on the object. Deleted objects return false
.
Open a write transaction with realm.write() or realm.writeBlocking().
Get the live objects by querying the transaction's MutableRealm for the objects that you want to delete using the query() method:
Specify the object type as a type parameter passed to
query()
.(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 SDK, refer to Read Objects.
Important
Objects Must Be Live
You can only delete live objects. If your query occurs outside of the write transaction, you must convert the frozen objects to live objects in the transaction with
mutableRealm.findLatest()
.Pass the set of RealmResults returned by the query to mutableRealm.delete().
The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isValid().
Deleted objects return false
.
Open a write transaction with one of the relevant APIs.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object, you query for the live version of the object on the local thread before deleting the object. For more details, refer to Threading.
Call the
delete()
method with the object you want to delete as an argument.The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isValid().
Deleted objects return false
.
Open a write transaction with transactionWithBlock or asyncTransactionWithBlock.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object or thread-safe reference, you must
thaw
the object or resolve the thread-safe reference before deleting the object. For more details, refer to Threading.Call the RLMRealm deleteObject method with the object to delete.
The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by checking the
invalidated
property. Deleted objects return true
.
Open a write transaction with one of the relevant APIs:
asyncWrite() and friends
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Important
Objects Must Be Live
You can only delete live objects. If you are working with a frozen object or thread-safe reference, you must
thaw()
the object or resolve the thread-safe reference before deleting the object. For more details, refer to Threading.Call the
delete()
method with the object you want to delete as an argument.The specified objects are deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isInvalidated().
Deleted objects return true
.
Open a write transaction with realm.write.
Pass the object(s) you want to delete into the write block, or query for them inside the block.
Call the delete method with the object you want to delete as an argument.
The specified object is deleted from the database and can no longer be accessed or modified. If you try to use a deleted object, the SDK throws an error.
If any deleted objects had a relationship with another object, the SDK only deletes the reference to the other object. The referenced object remains in the database, but it can no longer be queried through the deleted parent property. Refer to the Delete Related Objects section for more information.
Tip
You can check whether an object is still valid to use by calling
isValid
on the object. Deleted objects return false
.
Delete a Single Object
Tip
Use Unique Identifying Information
We recommend using unique identifying information to find the object you want to delete, such as a primary key value, to ensure your query returns the correct object.
To delete an object from the database, pass the object to the db.remove() function inside of a write transaction.
To delete an object from the database, pass the object to Realm.Remove() inside of a write transaction.
Delete an object from the database by calling Realm.delete() in a write transaction block.
To delete an object from the database, use either the dynamic or static
versions of the deleteFromRealm()
method of a RealmObject subclass.
The following example shows how to delete one object from its realm with deleteFromRealm().
To delete an object from the database, pass the object to Realm.delete() inside of a write transaction.
To delete a single RealmObject
object,
query for the object type using a filter
that returns the specific object that you want to delete.
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 database:
To delete an object from the database, use either the dynamic or static
versions of the deleteFromRealm()
method of a RealmObject subclass.
The following example shows how to delete one object from its realm with deleteFromRealm().
To delete an object from the database, pass the object to -[RLMRealm deleteObject:] inside of a write transaction.
To delete an object from the database, pass the object to Realm.delete(_:) inside of a write transaction.
To delete an object from the database, pass the object to Realm.delete() inside of a write transaction.
realm.write([&] { realm.remove(managedDog); });
realm.Write(() => { // Remove the instance from the realm. realm.Remove(dog); // Discard the reference. dog = null; });
realm.write(() { realm.delete(obiWan); });
realm.executeTransaction(r -> { // Get a turtle named "Tony". Turtle tony = r.where(Turtle.class).equalTo("name", "Tony").findFirst(); tony.deleteFromRealm(); // discard the reference tony = null; });
realm.write(() => { // Delete the dog from the realm. realm.delete(dog); // Discard the reference. dog = null; });
// 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) }
realm.executeTransaction { r: Realm -> // Get a turtle named "Tony". var tony = r.where(Turtle::class.java) .equalTo("name", "Tony") .findFirst() tony!!.deleteFromRealm() // discard the reference tony = null }
[realm transactionWithBlock:^() { // Delete the instance from the realm. [realm deleteObject:dog]; }];
// Previously, we've added a dog object to the realm. let dog = Dog(value: ["name": "Max", "age": 5]) let realm = try! Realm() try! realm.write { realm.add(dog) } // Delete the instance from the realm. try! realm.write { realm.delete(dog) }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete Multiple Objects
You can delete multiple objects within a write transaction.
To delete multiple objects at the same time, pass an IQueryable<T>
query
for the objects you want to delete to Realm.RemoveRange<T>.
Delete multiple objects from the database by calling Realm.deleteMany() in a write transaction block.
To delete an object from the database, use the deleteAllFromRealm()
method of the RealmResults
instance that contains the objects you would like to delete. You can
filter the RealmResults
down to a subset of objects using the
where() method.
The following example demonstrates how to delete a collection from the database with deleteAllFromRealm().
To delete a collection of objects from the database, pass the collection to Realm.delete() inside of a write transaction.
To delete multiple objects at the same time, pass the object type to
query()
and specify a query that returns all objects that you want
to delete.
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 database:
To delete an object from the database, use the deleteAllFromRealm()
method of the RealmResults
instance that contains the objects you would like to delete. You can
filter the RealmResults
down to a subset of objects using the
where() method.
The following example demonstrates how to delete a collection from the database with deleteAllFromRealm().
To delete a collection of objects from the database, pass the collection to -[Realm deleteObjects:] inside of a write transaction.
To delete a collection of objects from the database, pass the collection to Realm.delete(_:) inside of a write transaction.
To delete a collection of objects from the database, pass the collection to Realm.delete() inside of a write transaction.
// The documentation does not currently have this code example in C++. // Please refer to the other languages or related pages for example code.
realm.Write(() => { // Find dogs younger than 2 years old. var puppies = realm.All<Dog>().Where(dog => dog.Age < 2); // Remove the collection from the realm. realm.RemoveRange(puppies); });
realm.write(() { realm.deleteMany([obiWan, quiGon]); });
realm.executeTransaction(r -> { // Find turtles older than 2 years old. RealmResults<Turtle> oldTurtles = r.where(Turtle.class).greaterThan("age", 2).findAll(); oldTurtles.deleteAllFromRealm(); });
realm.write(() => { // Find dogs younger than 2 years old. const puppies = realm.objects("Dog").filtered("age < 2"); // Delete the collection from the realm. realm.delete(puppies); });
// 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) }
realm.executeTransaction { r: Realm -> // Find turtles older than 2 years old. val oldTurtles = r.where(Turtle::class.java) .greaterThan("age", 2) .findAll() oldTurtles.deleteAllFromRealm() }
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() { // Find dogs younger than 2 years old. RLMResults<Dog *> *puppies = [Dog objectsInRealm:realm where:@"age < 2"]; // Delete all objects in the collection from the realm. [realm deleteObjects:puppies]; }];
let realm = try! Realm() try! realm.write { // Find dogs younger than 2 years old. let puppies = realm.objects(Dog.self).where { $0.age < 2 } // Delete the objects in the collection from the realm. realm.delete(puppies) }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete All Objects of a Type
C++ does not currently provide an API to delete all objects of a type.
To delete all objects of a type, call Realm.RemoveAll<T>.
Delete all objects of a type in the database with Realm.deleteAll() in a write transaction block.
The following example demonstrates how to delete all Turtle instances from the database with delete().
To delete all objects of a given object type from the database, pass
Realm.objects(<ObjectType>)
to the Realm.delete() method inside of a write transaction.
To delete all objects of a specific type from the database 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 database:
The following example demonstrates how to delete all Turtle instances from the database with delete().
To delete all objects of a given object type from the database, pass
the result of +[YourSDKObjectClass
allObjectsInRealm:]
to -[Realm deleteObjects:]
inside of a write transaction. Replace YourSDKObjectClass
with your SDK object class name.
To delete all objects of a given object type from the database, query for objects of the type you want to delete, and pass the result to Realm.delete(_:) inside of a write transaction.
To delete all objects of a given object type from the database, pass
Realm.objects(<ObjectType>)
to the Realm.delete() method inside of a write transaction.
// The C++ SDK does not currently support this API.
realm.Write(() => { // Remove all instances of Dog from the realm. realm.RemoveAll<Dog>(); });
realm.write(() { realm.deleteAll<Person>(); });
realm.executeTransaction(r -> { r.delete(Turtle.class); });
realm.write(() => { // Delete all instances of Cat from the realm. realm.delete(realm.objects("Cat")); });
// 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) }
realm.executeTransaction { r: Realm -> r.delete(Turtle::class.java) }
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() { // Delete all instances of Dog from the realm. RLMResults<Dog *> *allDogs = [Dog allObjectsInRealm:realm]; [realm deleteObjects:allDogs]; }];
let realm = try! Realm() try! realm.write { // Delete all instances of Dog from the realm. let allDogs = realm.objects(Dog.self) realm.delete(allDogs) }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete All Objects in the Database
The SDK lets you delete all managed objects of all types, which is useful for quickly clearing out your database while prototyping. 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.
This does not affect the database schema or any objects that are not managed by the database instance.
C++ does not currently provide a method to delete all objects in the database. You can manually iterate through the objects and delete them if you need to clear the database.
To delete all managed objects in the database, call Realm.RemoveAll.
Dart does not provide an API to delete all objects in the database. Instead, you can iterate through the object types that the database manages and delete all objects of each type.
For more information, refer to the Delete All Objects of a Type section on this page.
The following example demonstrates how to delete everything from the database with deleteAll().
To delete all objects from the database, call Realm.deleteAll() inside of a write transaction. This clears the database of all object instances but does not affect the database schema.
To delete all objects from the database at the same time, call mutableRealm.deleteAll(). This deletes all objects of all types.
The following example demonstrates how to delete everything from the database with deleteAll().
To delete all objects from the database, call -[RLMRealm deleteAllObjects] inside of a write transaction. This clears the database of all object instances but does not affect the database's schema.
To delete all objects from the database, call Realm.deleteAll() inside of a write transaction. This clears the database of all object instances but does not affect the database's schema.
To delete all objects from the database, call Realm.deleteAll() inside of a write transaction. This clears the database of all object instances but does not affect the database schema.
// The C++ SDK does not currently support this API.
realm.Write(() => { // Remove all objects from the realm. realm.RemoveAll(); });
// The Flutter SDK does not currently support this API.
realm.executeTransaction(r -> { r.deleteAll(); });
realm.write(() => { // Delete all objects from the realm. realm.deleteAll(); });
// Open a write transaction realm.write { // Delete all objects from the realm deleteAll() }
realm.executeTransaction { r: Realm -> r.deleteAll() }
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() { // Delete all objects from the realm. [realm deleteAllObjects]; }];
let realm = try! Realm() try! realm.write { // Delete all objects from the realm. realm.deleteAll() }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete Related Objects
Deleting an object does not automatically delete any objects that are related to it unless the related object is embedded. Instead, the SDK only deletes the reference to the related object.
You can optionally define logic in your app to delete related objects. Or if an object lifecycle should not outlive a parent object, model it as an embedded object instead of an independent object with a relationship.
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 database:
// The documentation does not currently have this code example in C++. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript. // Please refer to the other languages or related pages for example code.
// 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) }
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete an Object and Its Related Objects
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 call Realm.RemoveRange<T>
to remove Ali's dogs
collection, which is a to-many list property
containing one or more Dog
objects. Then, we call Realm.Remove() to
delete Ali's Person
object itself.
The following example demonstrates how to perform a chaining delete by first deleting all of Ali's turtles, then deleting Ali.
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:
The following example demonstrates how to perform a chaining delete by first deleting all of Ali's turtles, then deleting Ali.
In the following example, we have a specific Person
object - ali
.
We delete the objects in Ali's dogs
collection, which is a to-many list
property containing one or more Dog
objects. Then, we delete the ali
Person
object itself.
In the following example, we delete the objects in the person.dogs
collection, which is a to-many list property containing one or more Dog
objects. Then, we delete the Person
object itself.
// The documentation does not currently have this code example in C++. // Please refer to the other languages or related pages for example code.
realm.Write(() => { // Remove all of Ali's dogs. realm.RemoveRange(ali.Dogs); // Remove Ali. realm.Remove(ali); });
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
realm.executeTransaction(r -> { // Find a turtle enthusiast named "Ali" TurtleEnthusiast ali = r.where(TurtleEnthusiast.class).equalTo("name", "Ali").findFirst(); // Delete all of ali's turtles ali.getTurtles().deleteAllFromRealm(); ali.deleteFromRealm(); });
// The documentation does not currently have this code example in JavaScript. // Please refer to the other languages or related pages for example code.
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) } }
realm.executeTransaction { r: Realm -> // Find a turtle enthusiast named "Ali" val ali = r.where(TurtleEnthusiast::class.java) .equalTo("name", "Ali").findFirst() // Delete all of ali's turtles ali!!.turtles!!.deleteAllFromRealm() ali.deleteFromRealm() }
[realm transactionWithBlock:^() { // Delete Ali's dogs. [realm deleteObjects:[ali dogs]]; // Delete Ali. [realm deleteObject:ali]; }];
let person = realm.object(ofType: Person.self, forPrimaryKey: 1)! try! realm.write { // Delete the related collection realm.delete(person.dogs) realm.delete(person) }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete an Embedded Object
Warning
The SDK Uses Cascading Deletes for Embedded Objects
When you delete a Realm
object, the SDK automatically deletes any
embedded objects referenced by that object. This is because embedded objects
are objects tha do not exist independent of the Realm
object, and do
not have their own lifecycle. If you want the referenced objects to persist
after the deletion of the main object, use a regular Realm
object with a
to-one relationship instead.
You can delete an embedded object through the parent object in a cascading delete or by deleting the embedded object directly.
To delete the embedded object through the parent object, fetch and delete the parent object. The SDK automatically deletes all of its embedded objects from the database.
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.
In the following example, we have a Business
object with a list of
embedded EmbeddedAddress
objects. We query for and delete the Business
object,
which automatically deletes all of its embedded EmbeddedAddress
objects:
// 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) }
In the following example, we have Contact
objects with embedded
EmbeddedAddress
objects. We delete an EmbeddedAddress
object directly and delete
another through the parent object:
// The documentation does not currently have this code example in C++. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript. // Please refer to the other languages or related pages for example code.
// 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 }
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete Property Values
Delete an Inverse Relationship
You can't delete an inverse relationship directly. Instead, an inverse relationship automatically updates by removing the relationship through the related object.
In this example, a Person
has a to-one relationship to a Dog
,
and the Dog
has an inverse relationship to Person
.
Setting the Person.dog
relationship to nullptr
removes the inverse
relationship from the Dog
object.
auto config = realm::db_config(); auto realm = realm::db(std::move(config)); auto dog = realm::Dog{.name = "Wishbone"}; auto [joe] = realm.write([&realm]() { auto person = realm::Person{.name = "Joe", .age = 27, .dog = nullptr}; return realm.insert(std::move(person)); }); // Assign an object with an inverse relationship // to automatically set the value of the inverse relationship realm.write([&dog, joe = &joe]() { joe->dog = &dog; }); CHECK(joe.dog->owners.size() == 1); // ... Later ... // Removing the relationship from the parent object // automatically updates the inverse relationship realm.write([joe = &joe]() { joe->dog = nullptr; }); CHECK(realm.objects<realm::Dog>()[0].owners.size() == 0);
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Kotlin. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Delete Mixed Property Values
Although mixed property instances cannot store null values, you can
delete a mixed property value by assigning your language's implementation of
null
or nil
directly to the property. For more information on the
mixed data type, refer to Generic (Mixed) Data Type.
To delete the value of a mixed property, set its value to Null
.
To delete the value of a mixed property, call RealmValue.nullValue()
.
To delete the value of a Mixed
property, set it to null
.
In the following example, we have a Frog
object with a list of
RealmAny
properties, and we clear the first RealmAny
property value:
To delete the value of an RLMValue
, set it to nil
.
To delete the value of an AnyRealmValue
, set it to .none
.
To delete the value of a Mixed
property, set it to null
.
// The documentation does not currently have this code example in C++. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript. // Please refer to the other languages or related pages for example code.
realm.write { val frog = query<Frog>().find().first() frog.favoriteThings[0] = null }
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
let realm = try! Realm() // Wolfie's companion is "Fluffy the Cat", represented by a string. // Fluffy has gone to visit friends for the summer, so Wolfie has no companion. let wolfie = realm.objects(Dog.self).where { $0.name == "Wolfie" }.first! try! realm.write { // You cannot set an AnyRealmValue to nil; you must set it to `.none`, instead. wolfie.companion = .none }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Remove Elements from Collections
SDK collection instances that contain objects only store references to those objects. You can remove one or more referenced objects from a collection without deleting the objects themselves. The objects that you remove from a collection remain in the database until you manually delete them. Alternatively, deleting an SDK object from a database also deletes that object from any collection instances that contain the object.
Remove Elements from a List
You can delete a list element
with erase()
, or remove all elements from the list with clear()
.
You can remove one or more elements from a list within a write transaction.
Deleting an object from the database will remove it from any lists
where it existed. Therefore, a list of objects will never contain deleted objects.
However, lists of primitive types can contain null values. If you do not
want to allow null values in a list, then either use non-nullable types in
the list declaration (for example, use IList<double>
instead of
IList<double?>
). If you are using the older schema
type definition (your classes derive from the RealmObject
base class),
or you do not have nullability enabled, use the [Required]
attribute if
the list contains nullable reference types, such as string
or byte[]
.
Important
Not Supported with Sync
Non-synced databases support collections of nullable (optional) values, but synced databases do not.
You can remove one or more elements from a RealmList within a write transaction:
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 contiguous elements from the list, pass the range to
list.removeRange()
.To remove the last element from the list, call
list.removeLast()
.To remove specific elements from a list that match a query, call
list.removeWhere()
.
For the available methods to remove elements from a list, refer to the RealmList API reference.
You can remove one or more elements from a List within a write transaction. Call list.remove() with the index of the element you want to remove.
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().
You can also remove all list elements at once by calling 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:
For the available methods to remove elements from a list, refer to the RealmList API reference.
You can remove one or more elements from a RLMArray within a write transaction:
To remove one element at a specified index in the list, pass the index to removeObjectAtIndex.
To remove the last element from the list, call removeLastObject.
You can also remove all list elements at once by calling removeAllObjects.
You can remove one or more elements from a List within a write transaction:
To remove one element at a specified index in the list, pass the index to list.removeAt().
To remove multiple contiguous elements from the list, pass the range to list.removeSubrange().
To remove the first N elements from the beginning or end of a list, call the list.removeFirst() or list.removeLast() methods with an Int number of items to remove from the beginning or end of the list.
You can also remove all list elements at once by calling list.removeAll().
You can remove one or more elements from a List within a write transaction. Call list.remove() with the index of the element you want to remove.
// The documentation does not currently have this code example in C++. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript. // Please refer to the other languages or related pages for example code.
// 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) }
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Remove Elements from a Set
You can delete a set element
with erase()
, or remove all elements from a set with clear()
.
You can remove one or more elements from a set within a write transaction.
Deleting an object from the database will remove it from any sets
in which it existed. Therefore, a set of objects will never contain null objects.
However, sets of primitive types can contain null values. If you do not
want to allow null values in a set, then either use non-nullable types in
the set declaration (for example, use ISet<double>
instead of
ISet<double?>
). If you are using the older schema
type definition (your classes derive from the RealmObject
base class),
or you do not have nullability enabled, you will need to use the
[Required]
attribute if the set contains nullable reference types, such as
string
or byte[]
.
Important
Not Supported with Sync
Non-synced databases support collections of nullable (optional) values, but synced databases do not.
You can remove one or more elements from a RealmSet within a write transaction:
To remove one element from the set, pass the element to
set.remove()
.To remove specific elements from a set that match a query, call
set.removeWhere()
.To remove all elements from the set, call
set.removeAll()
.
For the available methods to remove elements from a set, refer to the RealmSet API reference.
To remove a specific value from a set, pass the value to the
<Realm.Set>.delete()
method within a write transaction.
realm.write(() => { // remove the compass from playerOne's inventory by calling the // `delete()` method of the Realm Set object within a write transaction playerOne.inventory.delete("compass"); });
To remove all items from the set, run the <Realm.Set>.clear()
method within
a write transaction.
You can remove one or more elements in a single transaction from a RealmSet:
To remove one element from the set, pass the element you want to delete to set.remove().
To remove multiple elements from the set, pass the elements you want to delete to set.removeAll().
You can also remove all set elements at once by calling 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) }
In the following example, we have a Frog
object with a set of
Snack
objects. We remove all set elements with the set.clear()
method:
For the available methods to remove elements from a set, refer to the RealmSet API reference.
You can remove one or more elements from a RLMSet in a write transaction.
To remove one element from the set, call removeObject with the element you want to delete.
To remove from the receiving set elements that aren't a member of another set, call intersectSet with the other set as an argument.
To remove from the receiving set elements that are a member of another set, call minusSet with the other set as an argument.
You can remove all set elements at once by calling removeAllObjects.
You can delete specific elements from a MutableSet, or clear all of the elements from the set. If you are working with multiple sets, you can also remove elements in one set from the other set; see: Update a Set Property.
To remove a specific value from a set, pass the value to the
<Realm.Set>.delete()
method within a write transaction.
To remove all items from the set, run the <Realm.Set>.clear()
method within
a write transaction.
// Remove an element from the set with erase() auto it3064 = managedDocsRealm.openPullRequestNumbers.find(3064); CHECK(it3064 != managedDocsRealm.openPullRequestNumbers.end()); realm.write([&] { managedDocsRealm.openPullRequestNumbers.erase(it3065); }); CHECK(managedDocsRealm.openPullRequestNumbers.size() == 4); // Clear the entire contents of the set realm.write([&] { managedDocsRealm.openPullRequestNumbers.clear(); }); CHECK(managedDocsRealm.openPullRequestNumbers.size() == 0);
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
realm.write(() => { // clear all data from the inventory slot of playerTwo by calling // the `clear()` method of the Realm Set object in a write transaction playerTwo.inventory.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) }
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
let realm = try! Realm() // Record a dog's name and list of cities he has visited. let dog = Dog() dog.name = "Maui" let dogCitiesVisited = ["New York", "Boston", "Toronto"] try! realm.write { realm.add(dog) dog.citiesVisited.insert(objectsIn: dogCitiesVisited) } XCTAssertEqual(dog.citiesVisited.count, 3) // Later... we decide the dog didn't really visit Toronto // since the plane just stopped there for a layover. // Remove the element from the set. try! realm.write { dog.citiesVisited.remove("Toronto") } XCTAssertEqual(dog.citiesVisited.count, 2) // Or, in the case where the person entered the data for // the wrong dog, remove all elements from the set. try! realm.write { dog.citiesVisited.removeAll() } XCTAssertEqual(dog.citiesVisited.count, 0)
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Remove Dictionary Keys/Values
To delete a map key,
pass the key name to erase()
.
You can remove dictionary keys and values within a write transaction.
You can remove keys and values from a RealmMap within a write transaction. To remove a key and
its associated value, call map.remove()
. To remove an element matching
a query, call map.removeWhere()
.
For the available methods to remove dictionary keys and values, refer to the RealmMap API reference.
To delete members of a dictionary, use the dictionary.remove()
method with
an array of properties to remove from the dictionary.
You can remove RealmDictionary entries in a few ways:
To remove the value but keep the key, set the key to
null
(the dictionary's value must be nullable)To remove the key and the value, pass the key to remove()
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:
For the available methods to remove dictionary keys and values, refer to the RealmMap API reference.
You can remove RLMDictionary entries in a few ways:
To remove the value but keep the key, set the key to
null
(the dictionary's value must be nullable)To remove the key and the value, pass the key to removeObjectForKey
To remove keys specified by elements in a given array, pass the array to removeObjectsForKeys
You can also remove all keys and values by calling removeAllObjects.
You can delete map entries in a few ways:
Use
removeObject(for:)
to remove the key and the valueIf the dictionary's value is optional, you can set the value of the key to
.none
to keep the key. This sets the key's value tonil
but does not delete the key.Like a Swift dictionary, if you set the key value to
nil
, this deletes both the key and the value.If the value of a dictionary key is another object, and you delete the object, the key remains and its value is set to
nil
.
To delete members of a dictionary, use the dictionary.remove()
method with
an array of properties to remove from the dictionary.
realm.write([&] { tommy.locationByDay.erase("Tuesday"); });
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Dart. // Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
realm.write(() => { // remove the 'windows' and 'doors' field of the Summerhill House. summerHillHouse.remove(["windows", "doors"]); });
// 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()) }
// The documentation does not have this code example in Kotlin for the Java SDK. // Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C. // Please refer to the other languages or related pages for example code.
let realm = try! Realm() // Find the dog we want to update let wolfie = realm.objects(Dog.self).where { $0.name == "Wolfie" }.first! // Delete an entry try! realm.write { // Use removeObject(for:) wolfie.favoriteParksByCity.removeObject(for: "New York") // Or assign `nil` to delete non-optional values. // If the value type were optional (e.g. Map<String, String?>) // this would assign `nil` to that entry rather than deleting it. wolfie.favoriteParksByCity["New York"] = nil } XCTAssertNil(wolfie.favoriteParksByCity["New York"])
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.