I’m using Realm for Flutter/Dart and I’m trying to find out if or how it is possible to write a Realm query that uses the ANY collection operator but checks for multiple conditions.
A pseudo query could look like this:
ANY (items.priority == 1 AND items.isComplete == true)
Can someone confirm if there is a way to filter embedded collections like this?
And if so please give me some hint on how the query must look like.
Embedded Objects are filtered just like a regular collection. Are you filtering on the top level objects to return them based on their embedded objects?
e.g. pseudo code
User {
userName = "Jay"
embeddedDogs = list of Dog embedded objects
}
so the query will be on the User objects, not directly on the embeddedDog within the User object?
Yes this can be done but how it’s done will depend on the expected result.
Going back to this code
let me verbalize the query:
query users who have one or more embedded dog.status == healthy and one or more embedded dog.age >=3
e.g. any users where that have a dog in their embedded list that’s healthy and a dog in their embedded list whose age is 3 or greater. It could be two different dogs, one healthy and one age 3 or greater but as long as they are both in the users list.
It does NOT say that a single dog in their list must be healthy and have an age of 3 or greater.
While I have a solution, my brain only works in Swift. I think this (untested) solution would be accomplished through a Swift Subquery using NSPredicate.
let predicate = NSPredicate(
format: "SUBQUERY(
embeddedDogList, $dog, $dog.status == 'healthy' AND $dog.age >= 3).@count > 0"
)
let results = realm.objects(User.self).filter(predicate)
So we least know it can be done. Perhaps a flutter/dart expert can chime in.