I have a function in my MongoDB/Node backend that returns a list of departments.
The documents in the collection look like this:
[
{
_id: 111,
department: "abc"
},
{
_id: 222,
department: "def"
},
{
_id: 333,
department: "ghi"
}
]
This is working with aggregation looks like this:
$group: {
_id: null,
data: { $addToSet: "$department" }
}
However, what this produces is not ideal. The output looks like this:
{
"count": 1,
"data": [
{
"_id": null,
"data": [
"abc",
"def",
"ghi"
]
}
]
}
What I'd like to do is return data where there isn't a nested array structure with "data" inside "data". I'd like this output:
{
"count": 1,
"data": [
"abc",
"def",
"ghi",
]
}
Is there a way I can do this with a projection stage?
I tried this:
{
$group: {
_id: null,
data: { $addToSet: "$department" }
}
},
{
$project: {
data: 0,
_id: 0
}
}
But end up with the same data structure returned. Is there a way I can do this with $project?
UPDATE:
After a suggestion I tried this:
db.staffmembers.aggregate([
{
$group: {
_id: null,
data: { $addToSet: "$department" }
}
},
{
$project: {
data: {
$reduce: {
input: "$data.data",
initialValue: [],
in: {
$concatArrays: ["$$this", "$$value"]
}
}
}
}
}
]);
... but this outputs an empty array for data:
{
"_id" : null,
"data" : [
]
}