In our Realm Swift SDK we are using GraphQL. The query is an aggregate with two lookups, it takes quite long (3s+) until 10 results (of a collection with only 200 entries) are displayed.
Query code:
let aggregatePipeline: [Document] = [
"$match": [
"$and": [
[ "example": AnyBSON(stringLiteral: "test") ],
[ "_id": ["$ne": AnyBSON("123") ] ]
]
]
]
// realm database object loaded elsewhere
let collection = database.collection(withName: "Example")
do {
let resultObjectsRaw = try await collection.aggregate(pipeline: aggregatePipeline)
} catch {
print("error")
}
The query only took around 0.5s or less. The rest of the time is converting the result to our swift objects (Subclassed from RealmSwift
's Object
, see implementation below) (sometimes up to 1s per object). Is there a better way to convert the result of the query to swift objects?
This is what the result resultObjectsRaw
looks like:
array(
[
Optional(RealmSwift.AnyBSON.document([
"_id": Optional(RealmSwift.AnyBSON.string("xyz")),
"example": Optional(RealmSwift.AnyBSON.string("yzx"))
])),
Optional(RealmSwift.AnyBSON.document([
"_id": Optional(RealmSwift.AnyBSON.string("142")),
"example": Optional(RealmSwift.AnyBSON.string("647"))
]))
])
and we need it as an array of Swift objects. i.e:
class ExampleObject: Identifiable {
var id = UUID().uuidString
var example: String?
init(id: String? = nil, example: String? = nil) {
self.init()
if let id = id {
self.id = id
}
self.example = example
}
}
This is what we currently use to convert:
guard let documentId = document["_id"]??.stringValue else { return nil }
let property = document["example"]??.stringValue
// more properties ...
let object = ExampleObject(id: documentId, example: example) // creating the swift object
It should be noted that our actual objects have around 10 properties, where one property is a linked document (thus the lookup number 1) and this linked document once again has a linked document (thus lookup number 2). But all properties are either strings, Date objects or similarly "small" data.
P.S: There is this similar question on the MongoDB Community Forum, however it has no solution and is around a year old..