Ask Your Question
1

Is it possible to utilize ifNull to handle Nulls/undefined as if they were 0s during aggregation?

asked 2023-07-12 17:13:48 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-12 17:26:02 +0000

david gravatar image

Yes, it is possible to use ifNull to handle nulls/undefined as if they were 0s during aggregation. The syntax for using ifNull in aggregation is:

{$group: {
  _id: "$field",
  sum: {$sum: {$ifNull: ["$amount", 0]}}
}}

In the example above, if the value of the field "amount" is null or undefined, it will be treated as 0 for the purpose of calculating the sum.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-12 17:13:48 +0000

Seen: 13 times

Last updated: Jul 12 '23