concatenate string values in array to a single field in DocumentDB

0

Suppose that I have a series of documents with the following format:

{
"_id": "3_0",
"values": \["Test1", "Test2"]
}

and I would like to obtain a projection of the array's values concatenated in a single field:

{
"_id": "3_0",
"values": "Test1_Test2"
}

I could use following when i use mongodb, however, reduce is not supported in documentDB and I could not get this to work.
db.collection.aggregate([
{ "$addFields": {
"values": {
"$reduce": {
"input": "$values",
"initialValue": "",
"in": {
"$cond": {
"if": { "$eq": [ { "$indexOfArray": [ "$values", "$$this" ] }, 0 ] },
"then": { "$concat": [ "$$value", "$$this" ] },
"else": { "$concat": [ "$$value", "_", "$$this" ] }
}
}
}
}
}}
])

Could you please tell me if there's a workout. Thank you

Edited by: heshananupama on Feb 1, 2021 11:41 AM

Edited by: heshananupama on Feb 1, 2021 11:41 AM

Edited by: heshananupama on Feb 1, 2021 11:41 AM

Edited by: heshananupama on Feb 1, 2021 11:42 AM

gefragt vor 3 Jahren228 Aufrufe
1 Antwort
0

DocumentDB does support $reduce. for

rs0:PRIMARY> db.testc.find()
{ "_id" : "3_0", "values" : [ "Test1", "Test2" ] }
rs0:PRIMARY> db.testc.aggregate([ { "$addFields": { "values": { "$reduce": { "input": "$values", "initialValue": "", "in": { "$cond": { "if": { "$eq": [ { "$indexOfArray": [ "$values", "$$this" ] }, 0 ] }, "then": { "$concat": [ "$$value", "$$this" ] }, "else": { "$concat": [ "$$value", "_", "$$this" ] } } } } } }} ])
{ "_id" : "3_0", "values" : "Test1_Test2" }
rs0:PRIMARY> db.version()
4.0.0

AWS
Anva
beantwortet vor 2 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen