英文:
Group nested array to single array in mongodb
问题
以下是翻译好的部分:
我有一个聚合结果(包含两个对象的数组),如下所示:
[
{
"immunizationDetails": [
[
"Rubella"
],
[
"PCV13",
"Tdap"
]
}
},
{
"immunizationDetails": [
[
"Hepatitis B",
"HIB"
],
[
"PCV13"
]
}
}
]
但我需要将 immunizationDetails 放入一个单一数组中,如下所示:
[
{
"immunizationDetails": ["Rubella", "PCV13", "Tdap"]
},
{
"immunizationDetails": ["Hepatitis B", "HIB", "PCV13"]
}
]
需要有人的宝贵帮助。
英文:
I am having an aggregation result (an array of two objects) like this:
[
{
"immunizationDetails": [
[
"Rubella"
],
[
"PCV13",
"Tdap"
]
]
},
{
"immunizationDetails": [
[
"Hepatitis B",
"HIB"
],
[
"PCV13"
]
]
}
]
But I need immunizationDetails to be in a single array like this:
[
{
"immunizationDetails": ["Rubella", "PCV13", "Tdap"]
},
{
"immunizationDetails": ["Hepatitis B", "HIB", "PCV13"]
}
]
Need someone's valuable help.
答案1
得分: 1
只需添加一个$reduce
和 $concatArrays
以展平结果。
db.collection.aggregate([
{
"$set": {
"immunizationDetails": {
"$reduce": {
"input": "$immunizationDetails",
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
"$$this"
]
}
}
}
}
}
])
英文:
Just add one more $reduce
with $concatArrays
to flatten the result.
db.collection.aggregate([
{
"$set": {
"immunizationDetails": {
"$reduce": {
"input": "$immunizationDetails",
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
"$$this"
]
}
}
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论