Waws
Waws

Reputation: 203

Dynamic MongoDb queries in Grails

I have a domain similar to this in Grails

class User {
    static mapWith = "mongo"

    ObjectId id
    String name
    String address
    Integer age
}

I am building a search front-end in Grails to query a MongoDb database using the MongoDb plugin. Searching can be done on any of the fields in the database and any field that is not set by the user must be not be used in the query. I.e. no fields shall be compared to null. For example leaving all the fields empty returns all Users but searching for name returns only documents which matches on name.

Initially my queries was simple and I used User.find(new User(params)); in my controller which worked fine. Now I need to be able to also query integer fields using intervals, greater than and less than. I've looked at withCriteria() and to build the query depending on what fields the user have set but so far I've been unsuccessful.

TL;DR How can I do a query where I don't know which fields the user want to include in the query?

Upvotes: 1

Views: 1441

Answers (1)

Waws
Waws

Reputation: 203

I solved it by using withCriteria() like this:

def c = User.createCriteria()
def users = c.list {
    if(params.name)
        eq('name', params.name)
    if(params.address)
        eq('address', params.address)
    if(params.age_gt?.isInteger())
        gt('age', params.age_gt as Integer)
    if(params.age_lt?.isInteger())
        lt('age', params.age_lt as Integer)
}

Upvotes: 1

Related Questions