ANY operator with multiple conditions

Hello fellas,

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 I want to filter the top level objects based on the properties of their embedded objects.

Given your pseudo code I for example want to filter all Users that have any dog that is ‘status == healthy’ and ‘age >= 3’.

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.

Is that the expected result?

I already found out about the result your query describes.

Unfortunately no, it is not the expected result. I’m expecting it to be the same dog that fulfills the conditions.

So the user should only be included in the results if at least one dog is both health and over the age of 3.

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.

Jay, thank you very much.

Your query works like a charm. I’ve tested it on my own use case.

Apparently I was so dug into ANY that SUBQUERY just passed me by.

The Dart query looks pretty much identical.

final results =  realm
    .query<User>(r'SUBQUERY(embeddedDogList, $dog, $dog.status == "healthy" AND $dog.age >= 3).@count > 0');

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.