Turnary operator vs if/then/else comparison

Hi all, I have this aggregation:

[
    { $match: selectors },
    { $group: {
      _id: '$status',
      count: { $sum: 1 },
      anotherField: { $sum: { $cond: { if: { $eq: ['$isVerified', true] }, then: 1, else: 0 } } },
    } },
  ]

if i change the anotherField to a turnary operator like:

anotherField: { $sum: { $cond: [{ $eq: ['$isVerified', true] }, 1, 0] } },

will it be faster, since the if/then/else is removed?

Hello @nicoskk,

It’s a $cond conditional expression operator, there are two syntaxes, and both are the same in performance.

Hi @turivishal , thanks for replying, so performance is not affected not matter what the collection size is? When i run explain the results are inconsistent

Hi @nicoskk,

I am saying both syntaxes’ performance is the same,
Are you saying that both takes different execution times?
If yes then it is possible you will get difference in milliseconds, but if you have a problem with any specific syntax and getting a major difference then share the explain object for both the syntax.

1 Like