jkuehn / gorm-mongodb

Grails GORM implementation for the MongoDB document oriented database
http://www.grails.org/plugin/mongodb-morphia
Apache License 2.0
21 stars 14 forks source link

Advanced Querying using this plugin #9

Closed varunanand closed 12 years ago

varunanand commented 12 years ago

Hi,

I have been wanting some information on how to do some more advanced queries on the Mongo DB using the Grails Morphia plugin. I want to use query operators like $where, $or, etc.

I tried doing something like this but it didn't work,

def list = TestDomain.findAll(["where": "this.obj1.obj2.obj3 == 'dud' || this.obj1.obj2 == 'notdud' "], [max:100, validation: "false"])

But it seems to give me a validation error. Nevertheless I'm still not sure if this is the correct syntax or not. Haven't found anything on the net about this.

In the Morphia Library, it appears that you can do a DomainObject.where() and pass the Java Script condition as an argument. I really need this urgently as I won't be able to use Morphia without having OR / WHERE query options in my application.

Could you please let me know how this can be done from within the Grails Morphia Plugin?

Cheers,

Varun

jkuehn commented 12 years ago

Hi there,

it is planned to implement criteria queries for the mongodb-morphia plugin, which will support $or and $where queries. Currently your only way is to use morphia directly for such queries. Like this:

class TestController {
    def mongo // get the mongo handler injected

    def testMorphiaQuery() {
        Query q = mongo.datastore.createQuery(Car.class)
        q.where("this.name == 'X1' || (this.passenger && this.passenger.name == 'Joe')")

        println q.asList()
    }
}

mongo.datastore will return a configured AdvancedDatastore (http://morphia.googlecode.com/svn/site/morphia/apidocs/index.html) from morphia. Hope that helps

jkuehn commented 12 years ago

Also check out the new query method, which gives more convenient access to morphias query api:

With 0.7.5 you can do:

  def list = TestDomain.query([max:100]) { 
    where("this.obj1.obj2.obj3 == 'dud' || this.obj1.obj2 == 'notdud'") 
  }.asList()

see http://jkuehn.github.com/gorm-mongodb/ref/Domain%20Classes/query.html