Tanrikut
Tanrikut

Reputation: 548

How to write single sub id field in spring mongodb aggregation

I am trying to get following query from Spring Data Mongo Aggregation:

{
  "_id": {
    "year": "$_id.year"
  },
  "result": {
    "$push": {
      "rs": "$_id.rs",
      "vl": "$vl"
    }
  }
}

I tried following:

GroupAggregation as = group( "_id.year" ).push( new BasicDBObject( "rs", "$_id.rs" ).append( "vl", "$vl" ) ).as( "result" );

But it generates this expression where there is no sub field "year" under "_id" field:

{ "$group" : { "_id" : "$_id.year" , "result" : { "$push" : { "rs" : "$_id.rs" , "vl" : "$vl"}}}}  

Any ideas on how to get that query using spring data mongodb aggregation?

Upvotes: 0

Views: 573

Answers (1)

s7vr
s7vr

Reputation: 75914

I don't see any hook in the api to access the previous _id value.

You can use AggregationOperation to create $group stage using mongodb types.

Something like

AggregationOperation group = new AggregationOperation() {
       @Override
       public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
          return new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("year", "$_id.year" )).append("result", new BasicDBObject("$push", new BasicDBObject( "rs", "$_id.rs" ).append( "vl", "$vl" ))));
    } 
};

Upvotes: 1

Related Questions