Consultas dinámicas de MongoDb en 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?

preguntado el 01 de febrero de 12 a las 14:02

1 Respuestas

Lo resolví usando withCriteria() Me gusta esto:

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

Respondido 02 Feb 12, 11:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.