I'm currently using the Reduce
function to generate a combined String
of field
s from an array
.
For instance, suppose I have an array
of subdocuments
named children
- and each individual child
contains a name
field
.
For example:
[
{name:"Zak"}, {name:"Bob"}, {name:"Sharon"}, {name:"Zak"}, {name:"Cindy"}, {name:"Bob"}, {name:"Peter"}
]
By using the following expression
, I can produce a "csv" of
"Zak, Bob, Sharon, Zak, Cindy, Bob, Peter,"
:
(Yes, I am aware that I could potentially utilize $cond
to identify the last iteration and eliminate the trailing ", "
.
uniqueCsv: {
$reduce: {
input: "$children",
initialValue: '',
in: {
$concat: ["$$this.name", ", ", "$$value"]
}
}
}
Is there a way to use this reduce
function to remove duplicates and alphabetically sort
the names so that we end up with:
"Bob, Cindy, Peter, Sharon, Zak"
?
Thank you!