I have the following collection
{
"_id": "12345",
"Products": [
"Product1",
"Product2"
],
"State": "active",
}
And would like to project it similar to the output below
_id: "12345"
Products: "Product1, product2"
I tried this but im not getting the desired output of a comman seperated concatenated string
{
_id: 1,
Products: {
$reduce: {
input: "$Products",
initialValue:"0" ,
in: {concat: ["$$value", "$$this"] }
}
}
}
2
Answers
You can use
$reduce
and$concat
to concatenate the values into one string. The$cond
is necessary to determine if a comma is required between the values or not.See HERE for a working example.
This aggregation query gives the desired result:
The
$project
is used to transform theProducts
array of strings into a single concatenated string, using the$reduce
array operator.Note the usage of the
$ltrim
operator to remove the addition comma from the concatenated string, to give the following result:The projection of
_id
field is not explicitly required, it is by default projected.