title: Dynamic MongoDb queries in Grails
body: <p>I have a domain similar to this in Grails</p>
  
  <pre><code>class User {
      static mapWith = "mongo"
  
      ObjectId id
      String name
      String address
      Integer age
  }
  </code></pre>
  
  <p>I am building a search front-end in Grails to query a MongoDb database using the <a href="http://grails.org/plugin/mongodb" rel="nofollow">MongoDb plugin</a>. 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 <code>name</code> returns only documents which matches on <code>name</code>.</p>
  
  <p>Initially my queries was simple and I used <code>User.find(new User(params));</code> 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 <code>withCriteria()</code> and to build the query depending on what fields the user have set but so far I've been unsuccessful.</p>
  
  <p><strong>TL;DR</strong>
  How can I do a query where I don't know which fields the user want to include in the query?</p>