Question

I have a series of tags on an object, and I'd like to query for objects that contains all tags passed as an array. I know that operators in and inList translate to $in operator in MongoDB, but $in will return any object that contains at least one of the provided tags. I want objects that contain all provided tags. Or said another way $in means findAll tags with t1,or t2, or t3, etc. I want findAll tags with t1 AND t2 AND t3, etc. Mongodb fortunately supports the $all operator for that.

So how do I execute a query from Grail's GORM MongoDB plugin that will use the $all operator? Do I have to use the low level API? If so how do I get the lower level API to return my Domain objects fully populated?

Or Is there a better option for querying than using the $all operator that has better performance and let's me stay within criteria queries of GORM?

Was it helpful?

Solution

Ok I feel like I do this just about every couple of weeks, but here I go documenting MongoDB GORM since the authors just don't see it as important.

So $all is not supported. An alternative query is the following:

Photo.findAll {
    and {
       tagList.each { tag ->
          eq( 'tags', tag )
       }
    }
}

You can't use ==, but I don't have an explanation for that. I think I remember reading something about the each closure interfering, but I can't find it or remember where I saw it. Anyway you have to use eq() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top