0

How can I use Aggregation framework in Grails 1.3.7. At the moment i can't migrate into new version of grails. I have tried grails mongodb plugin 1.0.0.GA but it is using old java driver and gmongo libs. I have also tried to add dependencies for new libs/jars in build-config.groovy but still it is giving me error at runtime for aggregate method. Any help is highly appreciated.

1 Answers1

2

In your BuildConfig.groovy put this

dependencies {

    compile "org.mongodb:mongo-java-driver:2.10.1"
    runtime "com.gmongo:gmongo:1.1"
}

And then in plugin section

plugins {

    compile (":mongodb:1.1.0.GA"){
        excludes 'mongo-java-driver', 'gmongo'
    }
}

This will update your mongodb plugin to use the latest java drivers and gmongo.

Then use aggregation framework. Example

    DBObject match = new BasicDBObject('$match', new BasicDBObject("adPostId", 50) );

    // build the $projection operation
    DBObject fields = new BasicDBObject("adPostId", 1);
    fields.put("shopperId", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject('$project', fields );

    // Now the $group operation
    DBObject groupFields = new BasicDBObject( "_id", '$karmaType');
    groupFields.put("average", new BasicDBObject( '$sum', '$rating'));
    DBObject group = new BasicDBObject('$group', groupFields);

    // run aggregation
    AggregationOutput output = db.karma.aggregate( match, project, group );

return [model:[avgkarma:output.getCommandResult()]]

Ganesh Krishnan
  • 7,155
  • 2
  • 44
  • 52
  • where did you find ":mongodb:1.1.0.GA"? which repo are you using? My setup finds only RC3. In this case I'm getting java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.BytecodeInterface8. I tried both gmongo 1.0 and 1.1 and they are groovy 2.x based... – injecteer Jul 27 '13 at 23:11
  • Enable groovy 2.1 compiler and also make sure you uncomment the public respositories. – Ganesh Krishnan Jul 30 '13 at 02:01
  • 2.1 compiler is not an option, because my project uses about 30 other plugins – injecteer Jul 30 '13 at 13:22