Embedded Objects¶
Overview¶
An embedded object is a special type of Realm object that models complex data about a specific object. Embedded objects are similar to relationships, but they provide additional constraints and map more naturally to the denormalized MongoDB document model.
Realm enforces unique ownership constraints that treat each embedded object as nested data inside of a single, specific parent object. An embedded object inherits the lifecycle of its parent object and cannot exist as an independent Realm object. Realm automatically deletes embedded objects if their parent object is deleted or when overwritten by a new embedded object instance.
When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object. Any objects that your application must persist after the deletion of their parent object should use relationships instead.
Embedded Object Data Models¶
You can define embedded object types using either Realm object models or a server-side document schema. Embedded object types are reusable and composable. You can use the same embedded object type in multiple parent object types and you can embed objects inside of other embedded objects.
Embedded objects cannot have a primary key.
Realm Object Models¶
To specify that a Realm object model define an embedded object, derive the embedded object class from EmbeddedObject in Swift or RLMEmbeddedObject in Objective-C. You can reference an embedded object type from parent object types in the same way as you would define a relationship:
// Define an embedded object class Address: EmbeddedObject { dynamic var street: String? dynamic var city: String? dynamic var country: String? dynamic var postalCode: String? } // Define an object with one embedded object class Contact: Object { dynamic var _id = ObjectId.generate() dynamic var name = "" // Embed a single object. // Embedded object properties must be marked optional. dynamic var address: Address? override static func primaryKey() -> String? { return "_id" } convenience init(name: String, address: Address) { self.init() self.name = name self.address = address } } // Define an object with an array of embedded objects class Business: Object { dynamic var name = "" let addresses = List<Address>() // Embed an array of objects convenience init(name: String, addresses: [Address]) { self.init() self.name = name self.addresses.append(objectsIn: addresses) } }
JSON Schema¶
Unlike regular Realm objects, which map to their own MongoDB collection, embedded objects map to embedded documents in the parent type's document schema:
{ "title": "Contact", "bsonType": "object", "required": ["_id"], "properties": { "_id": "objectId", "name": "string", "address": { "title": "Address", "bsonType": "object", "properties": { "street": "string", "city": "string", "country": "string", "postalCode": "string" } } } }
{ "title": "Business", "bsonType": "object", "required": ["_id", "name", "addresses"], "properties": { "_id": "objectId", "name": "string", "addresses": { "bsonType": "array", "items": { "title": "Address", "bsonType": "object", "properties": { "street": "string", "city": "string", "country": "string", "postalCode": "string" } } } } }
Read and Write Embedded Objects¶
Create an Embedded Object¶
To create an embedded object, assign an instance of the embedded object to a parent object's property:
// Open the default realm let realm = try! Realm() try! realm.write { let address = Address() address.street = "123 Fake St" address.city = "Springfield" address.country = "USA" address.postalCode = "90710" let contact = Contact(name: "Nick Riviera", address: address) realm.add(contact) }
Update an Embedded Object Property¶
To update a property in an embedded object, modify the property in a write transaction:
// Open the default realm let realm = try! Realm() let idOfContactToUpdate = ObjectId("5f47f4811060b1aa6cc71272") // Find the contact to update by ID guard let contact = realm.object(ofType: Contact.self, forPrimaryKey: idOfContactToUpdate) else { print("Contact \(idOfContactToUpdate) not found") return } try! realm.write { // Update the embedded object directly through the contact contact.address?.street = "Hollywood Upstairs Medical College" contact.address?.city = "Los Angeles" contact.address?.postalCode = "90210" print("Updated contact: \(contact)") }
Overwrite an Embedded Object¶
To overwrite an embedded object, reassign the embedded object property of a party to a new instance in a write transaction:
// Open the default realm let realm = try! Realm() let idOfContactToUpdate = ObjectId("5f47f4811060b1aa6cc71272") // Find the contact to update by ID guard let contact = realm.object(ofType: Contact.self, forPrimaryKey: idOfContactToUpdate) else { print("Contact \(idOfContactToUpdate) not found") return } try! realm.write { let newAddress = Address() newAddress.street = "Hollywood Upstairs Medical College" newAddress.city = "Los Angeles" newAddress.country = "USA" newAddress.postalCode = "90210" // Overwrite the embedded object contact.address = newAddress print("Updated contact: \(contact)") }
Query a Collection on Embedded Object Properties¶
Use dot notation to filter or sort a collection of objects based on an embedded object property value:
It is not possible to query embedded objects directly. Instead, access embedded objects through a query for the parent object type.
// Open the default realm let realm = try! Realm() // Get all contacts in Los Angeles, sorted by street address let losAngelesContacts = realm.objects(Contact.self) .filter("address.city = %@", "Los Angeles") .sorted(byKeyPath: "address.street") print("Los Angeles Contacts: \(losAngelesContacts)")