MongoCXX: Is it possible to know when an aggregation pipeline "stopped" or finished with a merge?


I have an aggregation pipeline (using mongocxx driver) that executes a $redact with a $cond, something like this:


"$redact": {
	"$cond": {
		"if": {
			"$lte": [{
				"$sum": ["$slots", 1]
			}, 10]
		"then": "$KEEP",
        "else": "$PRUNE",

And the final stage includes a $merge, like this:


"$merge": {
  "into": "syncs_locks",
  "on": "_id",
  "whenMatched": "fail",
  "whenNotMatched": "insert"

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.

1 Like

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.