Aggregation unwind & group by condition

DB item:

{
name: "bicycle"
category: [ "transport", "sport" ],
status: "present" or "deleted"
}

I need result - categoryName: items quantity

const data = await Product.aggregate([
    {$unwind: "$category"},
    {$group: {_id: "$category", quantity: {$sum: 1}}}
  ])

But I tried to get only “present” items.

  const data = await Product.aggregate([
    {$unwind: "$category"},
    {$group: {_id: "$category", quantity: {
        $sum: { $cond: { if: { "status": "present" }, then: 1, else: 0}}
     }}}
  ])

result is the same !
Why my condition doesn’t work ?

Thats work

const getCategories = async(req, res) => {
  const data = await Product.aggregate([
    {$unwind: "$category"},
    {$group: {_id: "$category", quantity: {$sum: {
        $cond: [ {$eq: ["$status", "present"]}, 1, 0]
     }}}}
  ])
2 Likes

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