Docs Menu

Docs HomeRealm

UUID - Kotlin SDK

On this page

  • Create a UUID from a String
  • Create a Random UUID

UUID (Universal Unique Identifier) is a 16-byte unique value. You can use UUID as an identifier for objects. UUID is indexable, and you can use it as a primary key.

Realm Database creates UUIDs with the RealmUUID type that:

  • conform to RFC 4122 version 4

  • are created with random bytes

class Cat: RealmObject {
@PrimaryKey
var _id: RealmUUID = RealmUUID.random()
}

Note

Using UUID Instead of ObjectId

In general, you can use UUID for any fields that function as a unique identifier. Using UUID might be particularly useful if you are migrating data not stored in MongoDB since it is likely that your object's unique identifiers are already of a UUID type. Alternatively, using ObjectId might be useful for a collection of data that already exists in MongoDB.

To generate a new RealmUUID from a UUID formatted string, pass the string to RealmUUID.from():

realm.write {
this.copyToRealm(Cat().apply {
_id = RealmUUID.from("46423f1b-ce3e-4a7e-812f-004cf9c42d76")
})
}

To generate a random RealmUUID, call RealmUUID.random():

realm.write {
this.copyToRealm(Cat().apply {
_id = RealmUUID.random()
})
}
←  RealmSet - Kotlin SDKManage Realm Database Files - Kotlin SDK →
Share Feedback
© 2023 MongoDB, Inc.

About

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