Find groups's last positive value

Hi,
I am trying to build a aggretate query as below:
I have a list of data one of the fields is id and another field is value (can be +ve, -ve, 0).
I would like to group the data based on id and for each id I would like to get the last positive value.
I can find the last value of the group but what I wanted is last +ve value.
I have been trying out with $ne but its not working as expected.

[
  {id:"211204",value:12},
  {id:"211204",value:3},
  {id:"211205",value:5},
  {id:"211205",value:9},
  {id:"211205",value:-1},
  {id:"211205",value:0},
  {id:"211206",value:9},
  {id:"211206",value:6},
  {id:"211207",value:2},
  {id:"211207",value:0}
]

I would like to get :

[
  {id:"211204",value:3},
  {id:"211205",value:9}, # 9 as last value for that id is 0 and previous to that is -1 so previous value >= 1
  {id:"211206",value:6},
  {id:"211207",value:2} # 2 as last value for that id is 0 so previous >= 1 value
]

Match, then group.

db.foo.aggregate([
{$match: {"value": {$gt: 0}}}, 
{$group:{_id:"$id",value:{$first: "$value"}}}] )
2 Likes

Thanks @chris :slight_smile:
I was trying out the condition in group this whole time.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.