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

asked 2 years ago21 views
1 Answer
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

answered 5 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions