Create Specific Property Types
On this page
- Create Special Properties
- Create a Generic (Mixed) Property
- Create a Counter Property
- Create a Timestamp Property
- Create an Object ID Property
- Create a UUID Property
- Create Collection Properties
- Create List Properties
- Create Set Properties
- Create Dictionary Properties
- Create Relationship Properties
- Create a To-One Relationship
- Create a To-Many Relationship
- Create an Inverse Relationship
This page describes how to create specific property types, including:
Special SDK-specific types, such as counters or mixed data types
Collection property types, such as lists, sets, and maps
Relationship property types, including to-one, to-many, and inverse relationships
To learn more about how to define these property types in the object model, refer to Define an SDK Object Model.
For information about how to create specific types of objects, refer to Create Specific Object Types.
For information about write transactions and the methods you can use to create objects, refer to Create Objects.
Create Special Properties
Depending on how you define your object type, you might have properties that are special SDK-specific types. These may be custom data types, or familiar language types that have specific requirements or limitations when used with Atlas Device SDK.
Create a Generic (Mixed) Property
The SDK provides a generic mixed property type that could contain a number of property types. It's the closest analog to a polymorphic data type that the SDK provides.
For a list of the value types that a mixed property can hold, refer to Generic (Mixed) Data Type.
When you create an object with a realm::mixed
value, you must specify the
type of the value you store in the property. The SDK provides a type()
function you can call to determine what type of data the property has stored.
Note
You cannot create a nullable RealmValue
. However, if you want a
RealmValue
property to contain a null value, you can
use the special RealmValue.Null
property.
The following code demonstrates creating a RealmValue
property in a class
that inherits from IRealmObject
and then setting and getting the value of
that property:
To add a RealmValue
to an object, call RealmValue.from()
on the data
or RealmValue.nullValue()
to set a null value.
To create a RealmAny
instance, use the
RealmAny.valueOf() method
to assign an initial value or RealmAny.nullValue()
to assign no
value. RealmAny
instances are immutable just like String
or
Integer
instances; if you want to assign a new value to a
RealmAny
field, you must create a new RealmAny
instance.
Warning
Two Possible Null RealmAny Values
RealmAny
instances are always nullable. Additionally, instances can contain a
value of type RealmAny.Type.NULL
.
Create an object with a mixed value by running the realm.create() method within a write transaction.
To create a new object instance with a polymorphic
RealmAny
property, instantiate an object and pass an initial value of a
supported type to the RealmAny
property using
RealmAny.create().
After you create the object, you must know the stored value type
to work with the RealmAny
property.
In the following example, we instantiate a new Frog
object with a
favoriteThings
list of RealmAny
type and pass the initial values to
RealmAny.create()
:
To create a RealmAny
instance, use the
RealmAny.valueOf() method
to assign an initial value or RealmAny.nullValue()
to assign no
value. RealmAny
instances are immutable just like String
or
Integer
instances; if you want to assign a new value to a
RealmAny
field, you must create a new RealmAny
instance.
Warning
Two Possible Null RealmAny Values
RealmAny
instances are always nullable. Additionally, instances can contain a
value of type RealmAny.Type.NULL
.
When you create an object with an RLMValue
, you must specify the
type of the value you store in the property. The SDK provides an
RLMValue type
that you can use to determine what type of value the property has stored.
Later, when you read the mixed property type, you must check the type before you do anything with the value.
When you create an object with an AnyRealmValue
, you must specify the
type of the value you store in the property. The SDK provides an
AnyRealmValue enum that iterates
through all of the types the AnyRealmValue
can store.
Later, when you read the mixed property type, you must check the type before you do anything with the value.
Create an object with a mixed value by running the realm.create() method within 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.
public partial class MyRealmValueObject : IRealmObject { [ ] [ ] public Guid Id { get; set; } public RealmValue MyValue { get; set; } // A nullable RealmValue property is *not supported* // public RealmValue? NullableRealmValueNotAllowed { get; set; } private void TestRealmValue() { var obj = new MyRealmValueObject(); // set the value to null: obj.MyValue = RealmValue.Null; // or an int... obj.MyValue = 1; // or a string... obj.MyValue = "abc"; // Use RealmValueType to check the type: if (obj.MyValue.Type == RealmValueType.String) { var myString = obj.MyValue.AsString(); } }
final realm = Realm(Configuration.local([RealmValueExample.schema])); realm.write(() { // Use 'RealmValue.from()' to set values var anyValue = realm.add(RealmValueExample( // Add a single `RealmValue` value singleAnyValue: RealmValue.from(1), // Add a list of `RealmValue` values listOfMixedAnyValues: [Uuid.v4(), 'abc', 123].map(RealmValue.from), // Add a set of `RealmValue` values setOfMixedAnyValues: { RealmValue.from('abc'), RealmValue.from('def') }, // Add a map of string keys and `RealmValue` values mapOfMixedAnyValues: { '1': RealmValue.from(123), '2': RealmValue.from('abc') })); // Use 'RealmValue.nullValue()' to set null values var anyValueNull = realm.add(RealmValueExample( singleAnyValue: RealmValue.nullValue(), listOfMixedAnyValues: [null, null].map(RealmValue.from), setOfMixedAnyValues: {RealmValue.nullValue()}, mapOfMixedAnyValues: {'null': RealmValue.nullValue()}));
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
realm.write(() => { // create a Dog with a birthDate value of type string realm.create("Dog", { name: "Euler", birthDate: "December 25th, 2017" }); // create a Dog with a birthDate value of type date realm.create("Dog", { name: "Blaise", birthDate: new Date("August 17, 2020"), }); // create a Dog with a birthDate value of type int realm.create("Dog", { name: "Euclid", birthDate: 10152021, }); // create a Dog with a birthDate value of type null realm.create("Dog", { name: "Pythagoras", birthDate: null, }); });
realm.write { // Instantiate a new unmanaged Frog object with a RealmAny property val frog = Frog().apply { name = "Kermit" // Set initial values with RealmAny.create() favoriteThings = realmListOf( RealmAny.create(42), RealmAny.create("rainbows"), RealmAny.create(Frog().apply { name = "Kermit Jr." }) ) } // Copy the object to the realm to return a managed instance copyToRealm(frog) }
// 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.
// Create a Dog object and then set its properties let myDog = Dog() myDog.name = "Rex" // This dog has no companion. // You can set the field's type to "none", which represents `nil` myDog.companion = .none // Create another Dog whose companion is a cat. // We don't have a Cat object, so we'll use a string to describe the companion. let theirDog = Dog() theirDog.name = "Wolfie" theirDog.companion = .string("Fluffy the Cat") // Another dog might have a dog as a companion. // We do have an object that can represent that, so we can specify the // type is a Dog object, and even set the object's value. let anotherDog = Dog() anotherDog.name = "Fido" // Note: this sets Spot as a companion of Fido, but does not set // Fido as a companion of Spot. Spot has no companion in this instance. anotherDog.companion = .object(Dog(value: ["name": "Spot"])) // Add the dogs to the realm let realm = try! Realm() try! realm.write { realm.add([myDog, theirDog, anotherDog]) } // After adding these dogs to the realm, we now have 4 dog objects. let dogs = realm.objects(Dog.self) XCTAssertEqual(dogs.count, 4)
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Create a Counter Property
Some of the SDKs provide a special property type that you can use as a logical counter.
The C++ SDK does not currently provide a dedicated counter property type.
Traditionally, you would implement a counter by reading a value, incrementing
it, and then setting it (myObject.Counter += 1
). This does not work well in
an asynchronous situation like when two clients are offline. Consider
the following scenario:
The SDK object has a
counter
property of typeint
. It is currently set to a value of10
.Clients 1 and 2 both read the
counter
property (10
) and each increments the value by1
.When each client regains connectivity and merges their changes, they expect a value of 11, and there is no conflict. However, the counter value should be
12
!
When using a RealmInteger
, however, you can call the Increment()
and
Decrement()
methods, and to reset the counter, you set it to 0
, just as
you would an int
.
Important
When you reset a RealmInteger
, you may run into the offline merge issue
described above.
The Flutter SDK does not currently provide a dedicated counter property type.
Typically, incrementing or decrementing a
byte
, short
, int
, or long
field of a Realm
object looks something like this:
Read the current value of the field.
Update that value in memory to a new value based on the increment or decrement.
Write a new value back to the field.
When multiple distributed clients attempt this at the same time,
updates reaching clients in different orders can
result in different values on different clients. MutableRealmInteger
improves on this by translating numeric updates into sync operations
that can be executed in any order to converge to the same value.
The counter.increment() and counter.decrement() operators ensure that increments and decrements from multiple distributed clients are aggregated correctly.
To change a MutableRealmInteger value, call increment()
or
decrement()
within a write transaction.
You can assign a MutableRealmInteger
a new value with a call to
counter.set()
within a write transaction.
Warning
Counter Resets
Use the set()
operator with extreme care. set()
ignores
the effects of any prior calls to increment()
or decrement()
.
Although the value of a MutableRealmInteger
always converges
across devices, the specific value on which it converges depends on
the actual order in which operations took place.
Mixing set()
with increment()
and decrement()
is
not advised unless fuzzy counting is acceptable.
realm.executeTransaction(r -> { house.getGhosts().set(42); });
Since MutableRealmInteger
instances retain a reference to their
parent object, neither object can be garbage collected while you still
retain a reference to the MutableRealmInteger
.
To initialize a Counter, create
your object using the realm.create()
method. Pass in your object
schema and initial counter value, as well as initial
values for any other properties the object has.
After initialization, you can use the following methods to modify the counter value:
increment()
anddecrement()
update the underlying value by a specified number.set()
reassigns the counter to a specified value.
To create a new object instance with a
MutableRealmInt
property, instantiate an object and pass an initial value to the
MutableRealmInt
property using
MutableRealmInt.create().
For more information about the MutableRealmInt
type, refer to
Counter Data Type.
In the following example, we instantiate a new Frog
object with a
fliesEaten
property and pass an initial value to
MutableRealmInt.create()
:
Typically, incrementing or decrementing a
byte
, short
, int
, or long
field of a Realm
object looks something like this:
Read the current value of the field.
Update that value in memory to a new value based on the increment or decrement.
Write a new value back to the field.
When multiple distributed clients attempt this at the same time,
updates reaching clients in different orders can
result in different values on different clients. MutableRealmInteger
improves on this by translating numeric updates into sync operations
that can be executed in any order to converge to the same value.
The counter.increment() and counter.decrement() operators ensure that increments and decrements from multiple distributed clients are aggregated correctly.
To change a MutableRealmInteger value, call increment()
or
decrement()
within a write transaction.
You can assign a MutableRealmInteger
a new value with a call to
counter.set()
within a write transaction.
Warning
Counter Resets
Use the set()
operator with extreme care. set()
ignores
the effects of any prior calls to increment()
or decrement()
.
Although the value of a MutableRealmInteger
always converges
across devices, the specific value on which it converges depends on
the actual order in which operations took place.
Mixing set()
with increment()
and decrement()
is
not advised unless fuzzy counting is acceptable.
realm.executeTransaction { house!!.ghosts.set(42) }
Since MutableRealmInteger
instances retain a reference to their
parent object, neither object can be garbage collected while you still
retain a reference to the MutableRealmInteger
.
The Swift SDK does not currently provide a dedicated counter property type.
The Swift SDK does not currently provide a dedicated counter property type.
To initialize a Counter, create
your object using the realm.create()
method. Pass in your object
schema and initial counter value, as well as initial
values for any other properties the object has.
After initialization, you can use the following methods to modify the counter value:
increment()
anddecrement()
update the underlying value by a specified number.set()
reassigns the counter to a specified value.
// The C++ SDK does not currently support this API.
var myObject = realm.Find<MyRealmClass>(id); // myObject.Counter == 0 realm.Write(() => { // Increment the value of the RealmInteger myObject.Counter.Increment(); // 1 myObject.Counter.Increment(5); // 6 // Decrement the value of the RealmInteger // Note the use of Increment with a negative number myObject.Counter.Decrement(); // 5 myObject.Counter.Increment(-3); // 2 // Reset the RealmInteger myObject.Counter = 0; // RealmInteger<T> is implicitly convertable to T: int bar = myObject.Counter; });
// The Flutter SDK does not currently support this API.
HauntedHouse house = realm.where(HauntedHouse.class) .findFirst(); realm.executeTransaction(r -> { Log.v("EXAMPLE", "Number of ghosts: " + house.getGhosts().get()); // 0 house.getGhosts().increment(1); Log.v("EXAMPLE", "Number of ghosts: " + house.getGhosts().get()); // 1 house.getGhosts().increment(5); Log.v("EXAMPLE", "Number of ghosts: " + house.getGhosts().get()); // 6 house.getGhosts().decrement(2); Log.v("EXAMPLE", "Number of ghosts: " + house.getGhosts().get()); // 4 });
const myObject = realm.write(() => { return realm.create( myClass, { myCounter: 0 } ); });
realm.write { // Instantiate a new unmanaged Frog object with a MutableRealmInt property val frog = Frog().apply { name = "Michigan J. Frog" // Set an initial value with MutableRealmInt.create() fliesEaten = MutableRealmInt.create(200) } // Copy the object to the realm to return a managed instance copyToRealm(frog) }
val house = realm.where(HauntedHouse::class.java) .findFirst()!! realm.executeTransaction { Log.v("EXAMPLE", "Number of ghosts: ${house.ghosts.get()}") // 0 house.ghosts.increment(1) Log.v("EXAMPLE", "Number of ghosts: ${house.ghosts.get()}") // 1 house.ghosts.increment(5) Log.v("EXAMPLE", "Number of ghosts: ${house.ghosts.get()}") // 6 house.ghosts.decrement(2) Log.v("EXAMPLE", "Number of ghosts: ${house.ghosts.get()}") // 4 }
// The Swift SDK does not currently support this API.
// The Swift SDK does not currently support this API.
const myObject = realm.write(() => { return realm.create( myClass, { myCounter: 0 } ); });
Create a Timestamp Property
Use the chrono library
to store a time_point
relative to the system_clock
:
<std::chrono::time_point<std::chrono::system_clock>>
Use DateTimeOffset
to store timestamp data. The SDK converts
DateTimeOffset
values to UTC before storing in the database, and does not
store the timezone information.
See Issue #1835 for more information.
Use DateTime
to store timestamp data.
However, it is important to note that the SDK stores DateTime
in UTC.
When you use DateTime
, you must create it in UTC or convert it
with .toUtc()
before you store it. If your application requires it,
you can convert it back to local or the desired time zone when reading
from the database.
Use the Date
type to store timestamp data.
Use the date
property type to store timestamp data. This maps to the
JavaScript Date type.
To create a new object instance with a
RealmInstant
property, instantiate an object and pass an initial value to the
RealmInstant
property using either:
RealmInstant.from(): the epochSeconds and nanoseconds since the Unix epoch
RealmInstant.now(): the epochSeconds and nanoseconds since the Unix epoch until now
For more information about the RealmInstant
type, refer to
Timestamp Data Type.
In the following example, we instantiate a new Frog
object with a
birthdate
property and pass an initial value to RealmInstant.from()
:
Use the Date
type to store timestamp data.
Use the Objective-C NSDate
data type to store timestamp data.
Use the Swift Date
data type to store timestamp data.
Use the date
property type to store timestamp data. This maps to the
JavaScript Date type.
// 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.
// Create a Realm object with date in UTC, or convert with .toUtc() before storing final subaruOutback = realm.write<Vehicle>(() { return realm.add( Vehicle(ObjectId(), 'Subie', DateTime.utc(2022, 9, 18, 12, 30, 0))); }); final fordFusion = Vehicle(ObjectId(), 'Fuse', DateTime(2022, 9, 18, 8, 30, 0).toUtc()); realm.write(() { realm.add(fordFusion); }); // When you query the object, the `DateTime` returned is UTC final queriedSubaruOutback = realm.all<Vehicle>().query('nickname == "Subie"')[0]; // If your app needs it, convert it to Local() or the desired time zone final localizedSubieDateLastServiced = queriedSubaruOutback.dateLastServiced.toLocal();
// 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 { // Instantiate a new unmanaged Frog object with a RealmInstant property val frog = Frog().apply { name = "Kermit" // Set an initial value with RealmInstant.from() or RealmInstant.now() birthdate = RealmInstant.from(1_577_996_800, 0) } // Copy the object to the realm to return a managed instance copyToRealm(frog) }
// 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.
Create an Object ID Property
Create a unique Object ID with realm::object_id::generate()
.
Create a unique Object ID with ObjectId.GenerateNewId()
.
Call ObjectId()
to set any unique identifier properties of
your object. Alternatively, pass a string
to ObjectId()
to set the unique identifier property to a specific value.
Create a unique Object ID with new ObjectId()
.
You can initialize an ObjectId
using ObjectId()
.
Create a unique Object ID with ObjectId()
.
To create a random Object ID, call ObjectId.generate()
.
To create a zero-initialized Object ID, call ObjectId()
.
// 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.
final id = ObjectId(); final object = ObjectIdPrimaryKey(id);
// 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.
Create a UUID Property
You can create a UUID with realm::uuid()
. Or you can initialize a UUID
with a specific value, similar to realm::uuid("18de7916-7f84-11ec-a8a3-0242ac120002")
.
To set any unique identifier properties of
your object to a random value, call one of the Uuid
methods to create a UUID,
such as Uuid.v4()
.
You can generate a random RealmUUID
using RealmUUID.random()
or pass a UUID-formatted string to RealmUUID.from():
You can create a UUID with UUID()
.
// 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.
final myId = Uuid.v4(); final object = UuidPrimaryKey(myId);
// The documentation does not have this code example in Java. // Please refer to the other languages or related pages for example code.
const { UUID } = Realm.BSON; const ProfileSchema = { name: "Profile", primaryKey: "_id", properties: { _id: "uuid", name: "string", }, }; const realm = await Realm.open({ path: "realm-files/data-type-realm", schema: [ProfileSchema], }); realm.write(() => { realm.create("Profile", { name: "John Doe.", _id: new UUID(), // create a _id with a randomly generated UUID }); realm.create("Profile", { name: "Tim Doe.", _id: new UUID("882dd631-bc6e-4e0e-a9e8-f07b685fec8c"), // create a _id with a specific UUID value }); });
val uuid1 = RealmUUID.from("46423f1b-ce3e-4a7e-812f-004cf9c42d76") val uuid2 = RealmUUID.random()
// 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.
Create Collection Properties
The SDK provides the following collection type properties:
List
Set
Map
Collections are mutable within a write transaction.
Tip
Listen for Changes to a Created Collection
After you create a collection, you can register a notification handler to listen for changes. For more information, refer to Register a Collection Change Listener.
Create List Properties
The SDK's list data type is a container that holds a collection of primitive values or objects. These values may be of any supported type except another collection.
The SDK uses the List container type to define to-many relationships. A to-many relationship means that an object is related in a specific way to multiple objects.
For a list of the value types that a list property can hold, refer to Define a List Property.
To create an object with a list property (to-many relationship) to one or more objects:
Initialize the main object and the related objects
Use the push_back member function available to the SDK object lists to append the raw pointers of the related objects to the main object's list property
Move the object into the realm using the Realm.add() function inside of a write transaction.
In this example, we append the raw pointers of the related objects -
Employee *
- to the relationship property of the main object
- Company.employees
. This creates a one-way connection from the
Company
object to the Employee
objects.
Then, we add the Company
to the database. This copies the
Company
and Employee
objects to the database.
The related Employee
objects have their own lifecycle independent
of the main Company
object. If you delete the main object, the
related objects remain.
You can optionally create an inverse relationship to refer to the main object from the related object. For more information, refer to: Create an Inverse Relationship.
You create a list collection property by defining a getter-only property of type
IList<T>,
where T
can be any data type (except other collections).
You can create a relationship between one object and any number of objects
using a property of type List<T>
in your application, where T is an SDK
model class.
You can create a relationship between one object
and any number of objects using a field of type RealmList<T>
where T
is an SDK object in your application.
To define a to-many relationship, specify a property where the type is a list or array of the related SDK object type in its object schema.
To create a new object instance with a polymorphic
RealmAny
property, instantiate an object and pass an initial value of a
supported type to the RealmAny
property using
RealmAny.create().
After you create the object, you must know the stored value type
to work with the RealmAny
property.
In the following example, we instantiate a new Frog
object with a
favoriteThings
list of RealmAny
type and pass the initial values to
RealmAny.create()
:
You can create a relationship between one object
and any number of objects using a field of type RealmList<T>
where T
is an SDK object in your application.
Create an object with a mixed value by running the realm.create() method within a write transaction.
auto config = realm::db_config(); auto realmInstance = realm::db(std::move(config)); auto employee1 = realm::Employee{ ._id = 23456, .firstName = "Pam", .lastName = "Beesly"}; auto employee2 = realm::Employee{ ._id = 34567, .firstName = "Jim", .lastName = "Halpert"}; auto company = realm::Company{._id = 45678, .name = "Dunder Mifflin"}; // Use the `push_back` member function available to the // `ListObjectPersistable<T>` template to append `Employee` objects to // the `Company` `employees` list property. company.employees.push_back(&employee1); company.employees.push_back(&employee2); realmInstance.write([&] { realmInstance.add(std::move(company)); });
// The documentation does not currently have this code example in C#. // Please refer to the other languages or related pages for example code.
()class _Scooter { () late ObjectId id; late String name; late _Person? owner; } ()class _ScooterShop { () late ObjectId id; late String name; late List<_Scooter> scooters; }
// 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 { // Instantiate a new unmanaged Frog object with a RealmList property val frog = Frog().apply { name = "Kermit" // Set values for each unmanaged list favoritePonds.addAll(realmListOf( Pond().apply { name = "Picnic Pond" }, Pond().apply { name = "Big Pond" } )) favoriteForests.add(EmbeddedForest().apply { name = "Hundred Acre Wood" }) favoriteWeather = realmListOf("rain", "snow") } // Copy all objects to the realm to return managed instances copyToRealm(frog) }
// 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.
Create a Uint8List Property Type (Dart)
The Flutter SDK provides a Uint8List
from Dart. For more details about
defining a Uint8List
type, refer to
Define a Uint8List Property Type (Dart).
To add Uint8List
to a Realm object, call Uint8List.fromList()
on the data.
final realm = Realm(Configuration.local([BinaryExample.schema])); realm.write(() { realm.addAll([ BinaryExample("Example binary object", Uint8List.fromList([1, 2])) ]); });
Create Set Properties
Like their native counterparts, the SDK's set data type stores unique values. These values may be a Realm object or one of the supported data types. It cannot be another collection, an embedded object, or an asymmetric object.
The SDK uses the Set container type to define to-many relationships. A to-many relationship means that an object is related in a specific way to multiple objects.
For a list of the value types that a set property can hold, refer to Define a Set Property.
You can create objects that contain set properties as you would any SDK object, but you can only mutate a set property within a write transaction. This means you can only set the value(s) of a set property within a write transaction.
Add an object to a RealmSet
with
RealmSet.add().
Add multiple objects with RealmSet.addAll().
To create an object with a Realm Set property, you must create the object within a write transaction. When defining your SDK object, initialize the Realm Set by passing an empty array or an array with your initial values.
To create a new object instance with a polymorphic
RealmAny
property, instantiate an object and pass an initial value of a
supported type to the RealmAny
property using
RealmAny.create().
After you create the object, you must know the stored value type
to work with the RealmAny
property.
In the following example, we instantiate a new Frog
object with a
favoriteThings
list of RealmAny
type and pass the initial values to
RealmAny.create()
:
Add an object to a RealmSet
with
RealmSet.add().
Add multiple objects with RealmSet.addAll().
You can create objects that contain RLMSet properties as you would any SDK object, but you
can only mutate an RLMSet
within a write transaction. This means you can
only set the value(s) of a set property within a write transaction.
You can create objects that contain MutableSet properties as you would any SDK object, but you
can only mutate a MutableSet
within a write transaction. This means you can
only set the value(s) of a set property within a write transaction.
To create an object with a Realm Set property, you must create the object within a write transaction. When defining your SDK object, initialize the Realm Set by passing an empty array or an array with your initial values.
auto realm = realm::db(std::move(config)); // Create an object that has a set property auto docsRealmRepo = realm::Repository{.ownerAndName = "mongodb/docs-realm"}; // Add the object to the database and get the managed object auto managedDocsRealm = realm.write([&]() { return realm.add(std::move(docsRealmRepo)); }); // Insert items into the set auto openPullRequestNumbers = {3059, 3062, 3064}; realm.write([&] { for (auto number : openPullRequestNumbers) { // You can only mutate the set in a write transaction. // This means you can't set values at initialization, // but must do it during a write. managedDocsRealm.openPullRequestNumbers.insert(number); } });
// 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.
let playerOne, playerTwo; realm.write(() => { playerOne = realm.create("Character", { _id: new BSON.ObjectId(), name: "PlayerOne", inventory: ["elixir", "compass", "glowing shield"], levelsCompleted: [4, 9], }); playerTwo = realm.create("Character", { _id: new BSON.ObjectId(), name: "PlayerTwo", inventory: ["estus flask", "gloves", "rune"], levelsCompleted: [1, 2, 5, 24], }); });
realm.write { // Instantiate a new unmanaged Frog object with RealmSet properties val frog = Frog().apply { name = "Kermit" // Set initial values to each unmanaged set favoriteSnacks.addAll(setOf( Snack().apply { name = "flies" }, Snack().apply { name = "crickets" }, Snack().apply { name = "worms" } )) favoriteWeather.add("rain") } // Copy all objects to the realm to return managed instances copyToRealm(frog) }
// 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 current city let dog = Dog() dog.name = "Maui" dog.currentCity = "New York" // Store the data in a realm. Add the dog's current city // to the citiesVisited MutableSet try! realm.write { realm.add(dog) // You can only mutate the MutableSet in a write transaction. // This means you can't set values at initialization, but must do it during a write. dog.citiesVisited.insert(dog.currentCity) } // You can also add multiple items to the set. try! realm.write { dog.citiesVisited.insert(objectsIn: ["Boston", "Chicago"]) } print("\(dog.name) has visited: \(dog.citiesVisited)")
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Create Dictionary Properties
The SDK supports a dictionary (map) property type. Dictionary keys must be strings, but values can be any of the supported value types. For a list of the value types that a dictionary property can hold, refer to Define a Dictionary Property.
When you create an object that has a map property, you can set the values for keys in a few ways:
Set keys and values on the object and then add the object to the database
Set the object's keys and values directly inside a write transaction
Realm disallows the use of .
or $
characters in map keys.
You can use percent encoding and decoding to store a map key that contains
one of these disallowed characters.
// Percent encode . or $ characters to use them in map keys auto mapKey = "Monday.Morning"; auto encodedMapKey = "Monday%2EMorning";
Create an object with a dictionary value by running the realm.create() method within a write transaction.
To create a new object instance with a
RealmDictionary
property, instantiate an object and pass any key-value pairs of a
supported type to the RealmDictionary
property.
You can instantiate an unmanaged dictionary with realmDictionaryOf() or realmDictionaryEntryOf(). Or you can pass key-values using put() or putAll(). The dictionary is unmanaged until you copy it to the database.
Realm disallows the use of .
or $
characters in map keys.
You can use percent encoding and decoding to store a map key that contains
one of these disallowed characters.
// Percent encode . or $ characters to use them in map keys val mapKey = "Hundred Acre Wood.Northeast" val encodedMapKey = "Hundred Acre Wood%2ENortheast"
In the following example, we instantiate a new Frog
object with
initial key-values for several dictionary properties:
When you create an object that has a map property, you can set the values for keys in a few ways:
Set keys and values on the object and then add the object to the realm
Set the object's keys and values directly inside a write transaction
Use key-value coding to set or update keys and values inside a write transaction
Realm disallows the use of .
or $
characters in map keys.
You can use percent encoding and decoding to store a map key that contains
one of these disallowed characters.
// Percent encode . or $ characters to use them in map keys let mapKey = "New York.Brooklyn" let encodedMapKey = "New York%2EBrooklyn"
Create an object with a dictionary value by running the realm.create() method within a write transaction.
auto config = realm::db_config(); auto realm = realm::db(std::move(config)); auto employee = realm::Employee{ ._id = 8675309, .firstName = "Tommy", .lastName = "Tutone"}; employee.locationByDay = { {"Monday", realm::Employee::WorkLocation::HOME}, {"Tuesday", realm::Employee::WorkLocation::OFFICE}, {"Wednesday", realm::Employee::WorkLocation::HOME}, {"Thursday", realm::Employee::WorkLocation::OFFICE}}; realm.write([&] { realm.add(std::move(employee)); employee.locationByDay["Friday"] = realm::Employee::WorkLocation::HOME; });
// 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.
let johnDoe; let janeSmith; realm.write(() => { johnDoe = realm.create("Person", { name: "John Doe", home: { windows: 5, doors: 3, color: "red", address: "Summerhill St.", price: 400123, }, }); janeSmith = realm.create("Person", { name: "Jane Smith", home: { address: "100 northroad st.", yearBuilt: 1990, }, }); });
realm.write { val frog = Frog().apply { name = "Kermit" // Set initial key-values to each unmanaged dictionary favoriteFriendsByPond = realmDictionaryOf( "Picnic Pond" to Frog().apply { name = "Froggy Jay" }, "Big Pond" to Frog().apply { name = "Mr. Toad" } ) favoriteTreesInForest["Maple"] = EmbeddedForest().apply { name = "Hundred Acre Wood" } favoritePondsByForest.putAll( mapOf( "Silver Pond" to "Big Forest", "Big Lake" to "Elm Wood", "Trout Pond" to "Sunny Wood" ) ) } // Copy all objects to the realm to return managed instances copyToRealm(frog) }
// 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 current city let dog = Dog() dog.name = "Wolfie" dog.currentCity = "New York" // Set map values dog.favoriteParksByCity["New York"] = "Domino Park" // Store the data in a realm try! realm.write { realm.add(dog) // You can also set map values inside a write transaction dog.favoriteParksByCity["Chicago"] = "Wiggly Field" dog.favoriteParksByCity.setValue("Bush Park", forKey: "Ottawa") }
// The documentation does not currently have this code example in TypeScript. // Please refer to the other languages or related pages for example code.
Create Relationship Properties
When you have a property whose type references another SDK object, this creates a relationship between the objects. This can be a to-one, to-many, or inverse relationship. For more information about relationships, refer to Model Relationships.
Create a To-One Relationship
To create a new object instance with a to-one relationship property, instantiate both objects and pass the referenced object to the relationship property.
You can optionally create an inverse relationship to refer to the main object from the related object. For more information, refer to the Create an Inverse Relationship section on this page.
To create an object with a to-one relationship to another object, assign the raw pointer of the related object to the relationship property of the main object. Move the object into the database using the Realm.add() function inside of a write transaction.
In this example, we assign the raw pointer of the related object -
FavoriteToy *
- to the relationship property of the main object
- Dog.favoriteToy
. Then, when we add the dog
object to the
database, this copies both the dog
and favoriteToy
to the database.
The related favoriteToy
object has its own lifecycle independent
of the main dog
object. If you delete the main object, the related
object remains.
In the following example, we instantiate a new Frog
object with a
favoritePond
property that references a Pond
object and a
bestFriend
property that references another Frog
object:
auto config = realm::db_config(); auto realmInstance = realm::db(std::move(config)); auto favoriteToy = realm::FavoriteToy{ ._id = realm::uuid("68b696c9-320b-4402-a412-d9cee10fc6a5"), .name = "Wubba"}; auto dog = realm::Dog{ ._id = realm::uuid("68b696d7-320b-4402-a412-d9cee10fc6a3"), .name = "Lita", .age = 10, .favoriteToy = &favoriteToy}; realmInstance.write([&] { realmInstance.add(std::move(dog)); });
// 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 { // Instantiate a new unmanaged Frog object with to-one // relationship with a Realm object val frog = Frog().apply { name = "Kermit" age = 12 favoritePond = Pond().apply { name = "Picnic Pond" } bestFriend = Frog().apply { name = "Froggy Jay" } } // Copy all objects to the realm to return managed instances copyToRealm(frog) }
// 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.
Create a To-Many Relationship
To create a new object instance with a to-many relationship property, instantiate all objects and pass any referenced objects to the relationship collection property.
You may use a List or a Set to represent a to-many relationship, depending on whether you require the values to be unique, or whether you want to use any of the special collection type methods.
You can optionally create an inverse relationship to refer to the main object from the related object. For more information, refer to the Create an Inverse Relationship section on this page.
To create an object with a to-many relationship to one or more objects:
Initialize the main object and the related objects
Use the push_back member function available to the Realm object lists to append the raw pointers of the related objects to the main object's list property
Move the object into the realm using the Realm.add() function inside of a write transaction.
In this example, we append the raw pointers of the related objects -
Employee *
- to the relationship property of the main object
- Company.employees
. This creates a one-way connection from the
Company
object to the Employee
objects.
Then, we add the Company
to the realm. This copies the
Company
and Employee
objects to the realm.
The related Employee
objects have their own lifecycle independent
of the main Company
object. If you delete the main object, the
related objects remain.
In the following example, we instantiate a new Forest
object with a
frogsThatLiveHere
property that references a set of Frog
objects and a nearByPonds
property that references a list of
Pond
objects:
auto config = realm::db_config(); auto realmInstance = realm::db(std::move(config)); auto employee1 = realm::Employee{ ._id = 23456, .firstName = "Pam", .lastName = "Beesly"}; auto employee2 = realm::Employee{ ._id = 34567, .firstName = "Jim", .lastName = "Halpert"}; auto company = realm::Company{._id = 45678, .name = "Dunder Mifflin"}; // Use the `push_back` member function available to the // `ListObjectPersistable<T>` template to append `Employee` objects to // the `Company` `employees` list property. company.employees.push_back(&employee1); company.employees.push_back(&employee2); realmInstance.write([&] { realmInstance.add(std::move(company)); });
// 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 { // Instantiate a new unmanaged Forest object with to-many // relationship with multiple Realm objects val forest = Forest().apply { name = "Froggy Forest" frogsThatLiveHere = realmSetOf( Frog().apply { name = "Kermit" }, Frog().apply { name = "Froggy Jay" } ) nearbyPonds = realmListOf( Pond().apply { name = "Small Picnic Pond" }, Pond().apply { name = "Big Pond" } ) } // Copy all objects to the realm to return managed instances copyToRealm(forest) }
// 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.
Create an Inverse Relationship
To create a new object instance with an inverse relationship property, instantiate the parent object and pass any referenced child objects to the inverse relationship property.
After you create an object that has an inverse relationship, you can access the inverse relationship property to get the child objects. However, you cannot directly modify the backlink itself. For more information, refer to Update Inverse Relationships.
To create an object with a to-many relationship to one or more objects:
Initialize the main object and the related objects
Use the push_back member function available to the Realm object lists to append the raw pointers of the related objects to the main object's list property
Move the object into the realm using the Realm.add() function inside of a write transaction.
In this example, we append the raw pointers of the related objects -
Employee *
- to the relationship property of the main object
- Company.employees
. This creates a one-way connection from the
Company
object to the Employee
objects.
Then, we add the Company
to the realm. This copies the
Company
and Employee
objects to the realm.
The related Employee
objects have their own lifecycle independent
of the main Company
object. If you delete the main object, the
related objects remain.
In the following example, we instantiate a new Forest
object with a
frogsThatLiveHere
property that references a set of Frog
objects and a nearByPonds
property that references a list of
Pond
objects:
auto config = realm::db_config(); auto realm = realm::db(std::move(config)); auto dog = realm::Dog{.name = "Bowser"}; auto [jack, jill] = realm.write([&realm]() { auto person = realm::Person{.name = "Jack", .age = 27, .dog = nullptr}; realm::Person person2; person2.name = "Jill"; person2.age = 28; person2.dog = nullptr; return realm.insert(std::move(person), std::move(person2)); }); realm.write([&dog, jack = &jack]() { jack->dog = &dog; }); // After assigning `&dog` to jack's `dog` property, // the backlink automatically updates to reflect // the inverse relationship through the dog's `owners` // property CHECK(jack.dog->owners.size() == 1); realm.write([&dog, jill = &jill]() { jill->dog = &dog; }); // After assigning the same `&dog` to jill's `dog` // property, the backlink automatically updates CHECK(jill.dog->owners.size() == 2); CHECK(jack.dog->owners.size() == 2); // Removing the relationship from the parent object // automatically updates the inverse relationship realm.write([jack = &jack]() { jack->dog = nullptr; }); CHECK(jack.dog == nullptr); CHECK(jill.dog->owners.size() == 1);
// 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 { // Instantiate a new unmanaged User object with to-many // relationship with multiple Realm objects val post1 = Post().apply { title = "Forest Life" } val post2 = Post().apply { title = "Top Ponds of the Year!" } val user = User().apply { name = "Kermit" posts = realmListOf(post1, post2) } // Copy all objects to the realm to return managed instances copyToRealm(user) }
// 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.