'Realm Swift: advanced sum and aggregates

I have the following Realm Objects: each Patient object has multiple records, each Record has multiple entries, and for each entry there is a cost

class Patient: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var name: String = ""
    @Persisted var records: List<Record>
    
}

class Record: EmbeddedObject {
    @Persisted var date = Date()
    @Persisted var entries: List<Entry>
    
    @Persisted(originProperty: "records") var patient: LinkingObjects<Patient>

}

class Entry: EmbeddedObject {
    @Persisted var date = Date()
    @Persisted var type: String?
    @Persisted var cost: Int?

    @Persisted(originProperty: "entries") var record: LinkingObjects<Record>
}

Unfortunately I have just found that I can't query embedded objects directly, and I couldn't find a way to convert embedded objects into objects...

So my question is, how can I get the sum of costs for entries that are dated before a specific date?

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source