Docs Menu

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:

  1. Open a write transaction with realm.write() or realm.writeBlocking().
  2. 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.
  3. 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"

You can only modify objects in a realm within a write transaction.

←  Modify an Object - Kotlin SDKUpdate a Collection - Kotlin SDK →
Give Feedback
© 2022 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.