MarcF
MarcF

Reputation: 3299

Morphia aggregation stage group with object push

I'm using that latest version of morphia (1.3.2) and I'm trying to replicate the following succesfull mongodb aggregation stage in Java:

{
  _id: null,
  pv: { $push: { t: '$_id', c: '$c' }}
}

example input to stage is:

{ 
    "_id" : NumberLong(1487808017), 
    "c" : NumberInt(1)
}
{ 
    "_id" : NumberLong(1487808210), 
    "c" : NumberInt(1)
}
{ 
    "_id" : NumberLong(1487808914), 
    "c" : NumberInt(1)
}

and the expected output is:

{ 
    "_id" : null, 
    "pv" : [
        {
            "t" : NumberLong(1487808017), 
            "c" : NumberInt(1)
        }, 
        {
            "t" : NumberLong(1487808210), 
            "c" : NumberInt(1)
        }, 
        {
            "t" : NumberLong(1487808914), 
            "c" : NumberInt(1)
        }
}

The closest I have managed to get so far is:

.group(Group.grouping("pv", Accumulator.accumulator("$push", (Object) "{t: '$_id', c: '$c'}")))

but morphia is interpreting my accumulator as an explicit string.

If anyone could advise on the correct Java syntax to achieve this operation that would be greatly appreciated.

Upvotes: 3

Views: 649

Answers (1)

MarcF
MarcF

Reputation: 3299

Gah, after hours of searching, I worked out the answer within a few minutes of the OP:

.group(Group.grouping("pv", Group.grouping("$push", Projection.projection("t", "_id"), Projection.projection("c", "c"))))

I came across the possible solution while browsing the morphia tests here.

Upvotes: 3

Related Questions