Reputation: 69
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 ?
Upvotes: 0
Views: 68
Reputation: 223
You could try this.
db.collection.aggregate([
{
$addFields: {
"serviceCounties": [
{
$map: {
input: "$customerServices",
in: {
"countyName": "$$this.serviceCounty"
}
}
}
]
}
}
])
$addfields to add serviceCounties array
$map to get the customerServices values.
Upvotes: 1