3 / 3
May 2024

How can I build a condition without an else clause like this in a $set stage?

{ $set: { isLastReceiveTime: { $cond: { if: { "$eq": ["$last", true] }, then: "$$NOW" // No else clause } } } }

That is if the condition resolves to true “isLastReceiveTime” is set, otherwise it is untouched.
I found the suggestion to use an else clause like this:

{ $set: { isLastReceiveTime: { $cond: { if: { "$eq": ["$last", true] }, then: "$$NOW" , else: "$$REMOVE" } } } }

but this would remove an possibly already existing value in the isLastReceiveTime what is not what I want.

A workaround is to first store a possibly existing value of “isLastReceiveTime” in a temporary field and then use this in the else clause:

{ $set: { isLastReceiveTimeBack: "$isLastReceiveTime" isLastReceiveTime: { $cond: { if: { "$eq": ["$last", true] }, then: "$$NOW" , else: "$isLastReceiveTimeBack" } } } }

But this is a more than awkward way and would require to delete the new “isLastReceiveTimeBack” field in a later stage …

Hi Frank

Have you tried using:

else: "$isLastReceiveTime"

That should use the current value, unless there is something specific in your use case not stated.

Hope that helps.