I have the following result after a facet stage:
{
directComputers: [
{
_id: ObjectId('6139f794f6a0af371900dbfh'),
name: MyComputer_1
},
{
_id: ObjectId('6319bd1540b41d1a35717a16'),
name: MyComputer_2
}
],
indirectComputers: [
{
_id: ObjectId('6319bd1540b41d1a35717a16'),
name: MyComputer_2
},
{
_id: ObjectId('61f39f8ae2daa732deff6d90'),
name: MyComputer_3
}
]
I’m trying to add the objects from both arrays into a set (to avoid duplicates), and then unwind so I end up with one separate document for each object.
Like this:
{
_id: ObjectId('6139f794f6a0af371900dbfh'),
name: MyComputer_1
}
{
_id: ObjectId('6319bd1540b41d1a35717a16'),
name: MyComputer_2
}
{
_id: ObjectId('61f39f8ae2daa732deff6d90'),
name: MyComputer_3
}
How do I achieve that?
2
Answers
Since you want the results unwinded you can do:
See how it works on the playground example
Another option is which is more generic (for cases where
$unwind
is not needed):See how it works on the playground example
Assuming the objects inside your 2 arrays are completely identical(i.e. both
_id
andname
is the same and contains no other fields), you can use$setUnion
to construct the union. Then$unwind
and$replaceRoot
Mongo Playground
If you would rather compare with some key field, says
_id
in this case, you can use$reduce
to construct the union.Mongo Playground