The driver can catch “whenMatched” errors correctly with an exception.
But if the pipeline is executed “correctly”, either with a merge performed, or “stopped” in $redact, then, it is not possible to know what happened. The driver always returns an iterator that is always empty.
Is there any way to know if a document was inserted or modified? Or throw any exception if the cond was not met?
Hi @alvarolb, thanks for the great question! Unfortunately the information you’re trying to surface isn’t available as the $merge stage doesn’t offer any type of result reporting.
This is currently being tracked by SERVER-43194, and is in the backlog. Once this feature is prioritized, built and released downstream tools such as the C++ Driver would be able to surface these results after the aggregation pipeline completes.
The MongoDB aggregation framework provides an $out stage to write the results of an aggregation pipeline to a new collection. If the $out stage is included in the pipeline after the $redact stage, you can check the size of the new collection to determine if any documents were modified or inserted.
Alternatively, you can create a separate pipeline to check the size of the target collection before and after the aggregation pipeline, and compare the results to determine if any changes were made.
However, there is no direct method to throw an exception if the condition in the $cond stage was not met. You would have to add additional checks in your code to achieve this behavior.