Hi.
I have a collection in mongodb named Buffer in which documents are like this:
{ "load" : { "metric" : { "behind" : 35, "side" : 15, "top" : 135, "front" : 0 } } }
{ "load" : { "metric" : { "behind" : 35, "side" : 76, "top" : 120, "front" : 13 } } }
{ "load" : { "metric" : { "behind" : 47, "side" : 122, "top" : 0, "front" : 25 } } }
{ "load" : { "metric" : { "behind" : 67, "side" : 88, "top" : 11, "front" : 38 } } }
{ "load" : { "metric" : { "behind" : 100, "side" : 9, "top" : 42, "front" : 41 } } }
{ "load" : { "metric" : { "behind" : 119, "side" : 56, "top" : 12, "front" : 59 } } }
{ "load" : { "metric" : { "behind" : 131, "side" : 90, "top" : 34, "front" : 62 } } }
{ "load" : { "metric" : { "behind" : 165, "side" : 145, "top" : 56, "front" : 176 } } }
I wanted to use aggregation and calculate the average of side and top values. also I want to calculate the average of behind and front value together ,I mean calculating sum of front and behind value and then based on the that calculate average of these two fields. I got this working in the mongo shell and the command is as follow:
db.Buffer.aggregate([{$group:{"_id":null,"avgOfTop":{"$avg":"$load.metric.top"},"avgOfFront":{"$sum":"$load.metric.front"},"avgOfBehind":{"$sum":"$load.metric.behind"},"avgOfSide":{"$avg":"$load.metric.side"}}},{$project:{avgOfBackAndForth:{$avg:["$avgOfFront","$avgOfBehind"]},avgOfTop:1,avgOfSide:1,_id:0}}])
and the result is: { "avgOfTop" : 51.25, "avgOfSide" : 75.125, "avgOfBackAndForth" : 556.5 }
but I don't know how to do avg expression in the projection stage in
java.
my java code:
the results is : {"averageOfTop": 51.25, "averageOfSide": 75.125}
MongoDB documentation for java driver states that: "For $group accumulator expressions, the Java driver provides Accumulators helper class. For other aggregation expressions, manually build the expression Document."
but I don't know how to use compute() to build {avgOfBackAndForth:{$avg:["$avgOfFront","$avgOfBehind"]}
any help would be appreciated.