$reduce must output null if we pass null+1 as initialValue

I ran the below query -

>>> db.foo.find()
[
  { _id: 1, intV: 1, charV: 'a', stringV: 'abc', arrV: [ 1, 2 ] }
]

>>> db.foo.aggregate([ { $addFields: { total: { $reduce: { input: "$arrV",  initialValue:null+1, in: { $add: ["$$value", "$$this"] } } } } }])
[
  {
    _id: 1,
    intV: 1,
    charV: 'a',
    stringV: 'abc',
    arrV: [ 1, 2 ],
    total: 4
  }

It should return null and not 4.

Why do you think it should?

I think that 4 is the correct value. Despite the fact that we have

java script > 0 == null
> false
java script > 0 != null
> true

When null is use inside arithmetic expression it is converted to 0 as in the following.

java script > null + 1
> 1
java script > null - 5
> -5
java script > null * 6
> 0

So your initialValue: null+1, is really equivalent to 1.

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