Gergő Horváth
Gergő Horváth

Reputation: 3705

Mongo aggregate match + group with sum - return 0 if no matches

See playground. Here's the query:

db.collection.aggregate([
  {
    $match: {
      time: {
        $gte: 20,
        $lte: 40
      }
    }
  },
  {
    $group: {
      _id: null,
      amount: {
        $sum: "$amount"
      }
    }
  },
  {
    $project: {
      _id: 0,
      amount: 1
    }
  }
])

If no match found, it just returns an empty array. I would like it to return [{amount: 0}] even if no match. How is it possible?

Upvotes: 1

Views: 1786

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

Remove the $match pipeline and and add $cond inside $sum to process all the records.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      amount: {
        $sum: {
          "$cond": {
            "if": {
              "$and": [
                {
                  "$gte": [
                    "$amount",
                    20
                  ]
                },
                {
                  "$lte": [
                    "$amount",
                    40
                  ]
                },
              ]
            },
            "then": "$amount",
            "else": 0,
          }
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      amount: 1
    }
  }
])

Mongo Playground Sample Execution

Upvotes: 2

Related Questions