DaMatt91
DaMatt91

Reputation: 726

Return more counts for same field

Given the following document:

[
  {
    "user": "A",
    "feedback":"like"
  },
  {
    "user": "B",
    "feedback":"dislike"
  },
  {
    "user": "C",
    "feedback":"like"
  },
  {
    "user": "D",
    "feedback":"like"
  },
  {
    "user": "E",
    "feedback":"dislike"
  },
]

I would like to get likes count and dislikes count.

In this case I would get {likesCount: 3, dislikesCount: 2}.

How can I achieve this using Mongoose?

Upvotes: 1

Views: 37

Answers (1)

Takis
Takis

Reputation: 8695

Query

  • assuming that feedback and only be one of those 2 values
  • group by null (all collection 1 group)
    (null is a common choice, the point is to group by a constant "_id" : "hello" would do the same)
  • and 2 sums, if its like add to likesCount 1, else add 0 (the same for the dislikes)

Playmongo

yourColl.aggregate(
[{"$group": 
   {"_id": null,
    "likesCount": 
     {"$sum": {"$cond": [{"$eq": ["$feedback", "like"]}, 1, 0]}},
    "dislikesCount": 
     {"$sum": {"$cond": [{"$eq": ["$feedback", "dislike"]}, 1, 0]}}}}])

Upvotes: 2

Related Questions