Upsert an Object - Kotlin SDK
The upsert operation either inserts a new instance of an object or updates an existing object that meets certain criteria.
To upsert into a realm:
- Open a write transaction with realm.write() or realm.writeBlocking().
- Query the transaction's mutable realm with realm.query().
Specify the object type as a type parameter passed to
query()
. Filter your criteria with unique identifying criteria for the object you want to upsert. - Insert a new object with the same primary key as the object returned by the previous query (if it exists) with copyToRealm(). If an object matching your filter already exists, realm updates the existing object. If no object exists that matches your filter, realm inserts a new object.
realm.write { // fetch a frog from the realm based on some query val frog: Frog? = this.query<Frog>("name == 'Wirt'").first().find() // if the query returned an object, update object from the query if (frog != null) { frog.age = 4 frog.species = "Greyfrog" frog.owner = "L'oric" } else { // if the query returned no object, insert a new object with a new primary key. this.copyToRealm(Frog().apply { _id = Random.nextLong(1000000) name = "Wirt" age = 4 species = "Greyfrog" owner = "L'oric" }) } }
Note
You can only modify objects in a realm within a write transaction.