Last 20260123.md journal, I provided an example of duplicate documents when two pipelines are unioned. Now, to identify which document is a result of a particular pipeline, we can use $addFields aggregation stage. In the result, we can see which pipeline a document is associated to. This works by adding a new field to each document. In this case, we’re assigning src property with string literal value.
[
{
$match: {
gender: { $regex: ".*ale" }
}
},
{ $addFields: { src: "pipeline1" } },
{
$unionWith: {
coll: "persons",
pipeline: [
{
$match: {
gender: { $regex: ".*le" }
},
},
{ $addFields: { src: "pipeline2" } },
]
}
},
{ $sort: { _id: 1 } }
]
Sample result
[
{
"_id": {
"$oid": "696e23bbbea06b125b46d15e"
},
"id": 2,
"first_name": "Ashlee",
"last_name": "Alchin",
"email": "aalchin1@fema.gov",
"gender": "Female",
"ip_address": "157.142.117.33",
"src": "pipeline2"
},
{
"_id": {
"$oid": "696e23bbbea06b125b46d15e"
},
"id": 2,
"first_name": "Ashlee",
"last_name": "Alchin",
"email": "aalchin1@fema.gov",
"gender": "Female",
"ip_address": "157.142.117.33",
"src": "pipeline1"
}
]