any way I can get a single value instead of an array with nulls?
Hi Jack,
You can use the $group operator with $addToSet to combine results into a set of unique names without nulls.
Commented example based on your schema sample:
db.foo.aggregate(
// Find values of 'color' for each document
{ $project : { a : "$attribs.color" }},
// Unwind 'color' matches per document into single array
{ $unwind : "$a" },
// Group unique names into a set (removing nulls) .. must specify _id
{ $group : {
_id: "colors",
colors: { $addToSet: "$a" }
}},
// Final output, with unwanted _id field removed
{ $project : {
'_id' : 0,
'colors' : 1,
}}
)
The last step in the pipeline ($project to remove _id) isn't strictly needed if you just want the colors[] array created in the $group step.
A helpful way to understand how the operators manipulate the results is to add one pipeline step at a time (eg. just $project, then $project + $unwind, ..).
My sample output:
{
"result" : [
{
"colors" : [
"green",
"red"
]
}
],
"ok" : 1
}
Cheers,
Stephen