Count values in array of objects

Something like:

db.collection.aggregate([  
    { "$unwind": "$votes" },
    { "$group": {
      "_id": "$name",
      "ups": {$sum: {$cond: {"if": {"$eq": ["$votes.action","up"]},then: 1,else: 0}}},
      "not_ups": {$sum: {$cond: {"if": {"$ne": ["$votes.action","up"]},then: 1,else: 0}}},
      "score": {$sum: {$cond: {"if": {"$eq": ["$votes.action","up"]},then: 1,else: -1}}}}
    }])

should get you there…
You might want to account for “dirty” data where an action is neither up nor down in some way too?

Check out Mongo playground

1 Like