I have an API endpoint that checks the mongo db and returns in a following structure for example:
{ "Name": "Test" "Location": "Whatever", "customerServices": [ { "id": "test", "cusId": "test", "serviceAdr": "test", "serviceCounty": "West", "name": "test" }, { "id": "test", "cusId": "test", "serviceAdr": "test", "serviceCounty": "West", "name": "test" }, { "id": "test", "cusId": "test", "serviceAdr": "test", "serviceCounty": "East", "name": "test" } ] }
What I want to do is to add aggregation to the pipeline that would create additional field-serviceCounties and include distinct serviceCounty values from the customerServices array. Like the following:
{ "Name": "Test" "Location": "Whatever", "customerServices": [ { "id": "test", "cusId": "test", "serviceAdr": "test", "serviceCounty": "West", "name": "test" }, { "id": "test", "cusId": "test", "serviceAdr": "test", "serviceCounty": "West", "name": "test" }, { "id": "test", "cusId": "test", "serviceAdr": "test", "serviceCounty": "East", "name": "test" } ], "serviceCounties": [ { "countyName":"East" }, { "countyName":"West" } ] }
I have tried the following, but it didn't work. There something I'm missing or doing wrong:
'serviceCounties': { '$reduce': { 'input': '$services.event.services', 'initialValue': [], 'in': [{ "countyName": { '$concatArrays': ["$$value.serviceCounty", "$$this"] } }] } }
Any ideas how to do it ?
https://stackoverflow.com/questions/65803981/how-to-aggregate-distinct-items-in-mongo-db-to-separate-array January 20, 2021 at 02:12PM
没有评论:
发表评论