Navigation

Writes

Realm Database uses a highly efficient storage engine to persist objects. You can create objects in a realm, update objects in a realm, and eventually delete objects from a realm. Because these operations modify the state of the realm, we call them writes.

Realm Database handles writes in terms of transactions. A transaction is a list of read and write operations that Realm Database treats as a single indivisible operation. In other words, a transaction is all or nothing: either all of the operations in the transaction succeed or none of the operations in the transaction take effect.

Info With Circle IconCreated with Sketch.Note

All writes must happen in a transaction.

A realm allows only one open transaction at a time. Realm Database blocks other writes on other threads until the open transaction is complete. Consequently, there is no race condition when reading values from the realm within a transaction.

When you are done with your transaction, Realm Database either commits it or cancels it:

  • When Realm Database commits a transaction, Realm Database writes all changes to disk. For synced realms, Realm Database queues the change for synchronization with MongoDB Realm.
  • When Realm Database cancels a write transaction or an operation in the transaction causes an error, all changes are discarded (or "rolled back").

Realm Database guarantees that transactions are ACID compliant. This means that all committed write operations are guaranteed to be valid and that clients don't see transient states in the event of a system crash.

Realm Database represents each transaction as a callback function that contains zero or more read and write operations. To run a transaction, define a transaction callback and pass it to the realm's write method. Within this callback, you are free to create, read, update, and delete on the realm. If the code in the callback throws an exception when Realm Database runs it, Realm Database cancels the transaction. Otherwise, Realm Database commits the transaction immediately after the callback.

Important With Circle IconCreated with Sketch.Important
Concurrency Concerns

Since transactions block each other, it is best to avoid opening transactions on both the UI thread and a background thread. If you are using Sync, avoid opening transactions on the UI thread altogether, as Realm Database processes synchronizations on a background thread. If a background transaction blocks your UI thread's transaction, your app may appear unresponsive.

Beaker IconExample

The following code shows how to run a transaction with the realm's write method. If the code in the callback throws an exception, Realm Database cancels the transaction. Otherwise, Realm Database commits the transaction.

realm.write(() => {
// Create someone to take care of some dogs.
const ali = realm.create("Person", { id: 1, name: "Ali" });
// Find dogs younger than 2.
const puppies = realm.objects("Dog").filtered("age < 2");
// Loop through to update.
puppies.forEach(puppy => {
// Give all puppies to Ali.
puppy.owner = ali;
});
});

In general, instantiate Realm objects as you would any other object. In a transaction, you can add the object to the realm if the realm's schema includes the object type. When you add an instance to the realm, it becomes managed by that realm.

With the Java and JavaScript SDKs, instead use the realm's factory method in a transaction to instantiate your class. This automatically inserts the instance into the realm.

Beaker IconExample

This code demonstrates how to create an object with Realm Database:

// Declare the instance.
let dog;
// Open a transaction.
realm.write(() => {
// Assign a newly-created instance to the variable.
dog = realm.create("Dog", { name: "Max", age: 5 });
});

An upsert is a write operation that either inserts a new object with a given primary key or updates an existing object that already has that primary key. We call this an upsert because it is an "update or insert" operation. This is useful when an object may or may not already exist, such as when bulk importing a dataset into an existing realm. Upserting is an elegant way to update existing entries while adding any new entries.

Beaker IconExample

This code demonstrates how to upsert an object with realm. We create a new user named "Drew" and then update their name to "Andy" via upsert:

realm.write(() => {
// Add a new person to the realm. Since nobody with ID 1234
// has been added yet, this adds the instance to the realm.
const drew = realm.create("Person", { id: 1234, name: "Drew" }, "modified");
// Judging by the ID, it's the same person, just with a different name.
// If an object exists, setting the third parameter (`updateMode`) to
// "modified" only updates properties that have changed, resulting in
// faster operations.
const andy = realm.create("Person", { id: 1234, name: "Andy" }, "modified");
});

Within a transaction, you can update a Realm object the same way you would update any other object in your language of choice: just assign a new value to the property or update the property.

Beaker IconExample

This code changes the dog's name to "Wolfie" and increments the age by 1:

// Open a transaction.
realm.write(() => {
// Get a dog to update.
const dog = realm.objects("Dog")[0];
// Update some properties on the instance.
// These changes are saved to the realm.
dog.name = "Wolfie";
dog.age += 1;
});

Realm Database supports collection-wide updates. A collection update applies the same update to specific properties of several objects in a collection at once.

Beaker IconExample

The following code demonstrates how to update a collection. Thanks to the implicit inverse relationship between the Dog's owner property and the Person's dogs property, Realm Database automatically updates Ali's list of dogs.

realm.write(() => {
// Create someone to take care of some dogs.
const ali = realm.create("Person", { id: 1, name: "Ali" });
// Find dogs younger than 2.
const puppies = realm.objects("Dog").filtered("age < 2");
// Loop through to update.
puppies.forEach(puppy => {
// Give all puppies to Ali.
puppy.owner = ali;
});
});

In general, to delete an object from a realm, pass the instance to the delete method of the realm within a transaction.

With the Java SDK, call deleteFromRealm() on the instance itself.

Important With Circle IconCreated with Sketch.Important
Do not use objects after delete

Realm Database throws an error if you try to use an object after it has been deleted.

Beaker IconExample

The following code shows how to delete one object from its realm:

realm.write(() => {
// Delete the dog from the realm.
realm.delete(dog);
// Discard the reference.
dog = null;
});

In general, to delete a collection of objects from a realm, pass the collection to the delete method of the realm within a transaction.

With the Java SDK, call deleteFromRealm() on the collection itself.

Beaker IconExample

The following code demonstrates how to delete a collection from a realm:

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);
});

When you delete a non-embedded object with a relationship to a child object, Realm does not automatically delete the child object.

Info With Circle IconCreated with Sketch.Note
Automatically Deleting Embedded Objects

If you would like to automatically delete an object, you must make the object an Embedded Object. When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object.

Beaker IconExample

In the following example, Ali is a Person who is the owner of many dogs. The code block demonstrates how to delete an object that is related to another object by first deleting all of Ali’s dogs, then deleting Ali:

realm.write(() => {
// Delete all of Ali's dogs.
realm.delete(ali.dogs);
// Delete Ali.
realm.delete(ali);
});

Realm Database supports deleting all instances of a Realm type from a realm.

Beaker IconExample

The following code demonstrates how to delete all Dog instances from a realm:

realm.write(() => {
// Delete all instances of Dog from the realm.
realm.deleteModel("Dog");
});

It is possible to delete all objects from the realm. This does not affect the schema of the realm. This is useful for quickly clearing out your realm while prototyping.

Beaker IconExample

The following code demonstrates how to delete everything from a realm:

realm.write(() => {
// Delete all objects from the realm.
realm.deleteAll();
});
  • Realm Database handles writes in terms of transactions. All writes must occur in a transaction.
  • Realm Database transactions are ACID compliant.
  • To write to Realm Database, define the transaction in a callback function that you pass to the realm's write method.
Give Feedback