I have a document with an array field named enabled_domain
with 1, 2 or more elements. I need to flatten this array into a new field so it will be a string field with the concatenation of all the array field elements separated by comma, for example.
What I have done so far is:
db.myCollection.aggregate(
[
{
$project: {
enabled_domain_2: {
$reduce: {
input: "enabled_domain",
initialValue: "",
in: {
$concat: [ '$$value', '$$this' ]
}
}
}
}
}
]
)
... but it does not work.
A sample of myCollection
is:
{
"_id" : ObjectId("56c1fd43e4b0a6078c98108f"),
"enabled_domain" : [
"A",
"B"
]
}
/* 2 */
{
"_id" : ObjectId("5436044fb700a771a18eeac0"),
"enabled_domain" : [
"A"
]
}
How can I make this operation? Thanks in advance.
You just need to add dollar sign in $reduce
to reference existing array:
db.myCollection.aggregate(
[
{
$project: {
enabled_domain_2: {
$reduce: {
input: "$enabled_domain",
initialValue: "",
in: {
$concat: [ '$$value', '$$this' ]
}
}
}
}
}
]
)
That's what you're missing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.