![](/img/trans.png)
[英]How to use aggregation to pull information from a nested array on objects in mongoDB
[英]Pull out array of objects and use their fields out of the array (MongoDB aggregation framework)
我不知道這是否可行,但假設我有這樣的文件:
[
{
"L": [
{
"L1": 1
},
{
"L6": 2
},
{
"L2": 1
}
],
"week": 26,
"weekEnd": "2020-06-28",
"weekStart": "2020-06-22"
},
{
"L": [
{
"L5": 1
},
{
"L2": 1
},
{
"L3": 1
}
],
"week": 19,
"weekEnd": "2020-05-10",
"weekStart": "2020-05-04"
},
]
正如大家所看到的,數組L
可以有不同的對象,其中包含L1, L2, L3, ..., L30
等字段。
我想從L
數組中取出每個 object 的字段。
預期結果:
[
{
"L1": 1,
"L6": 2,
"L2": 1,
"week": 26,
"weekEnd": "2020-06-28",
"weekStart": "2020-06-22"
},
{
"L5": 1,
"L2": 1,
"L3": 1,
"week": 19,
"weekEnd": "2020-05-10",
"weekStart": "2020-05-04"
}
]
我可以“從頭開始”做到這一點,但我必須在$project
階段一個一個地編寫每個字段。 有自動的方法嗎?
您可以使用$mergeObjects
(從 v3.6 開始提供)來合並數組中對象的所有鍵。 首先,您必須合並數組L
中的對象,然后您必須將結果與根文檔$$ROOT
合並
db.collection.aggregate({
$replaceRoot: { // 3. replace the result as root document
newRoot: {
$mergeObjects: [ // 2. merge with root document
{
$mergeObjects: "$L" // 1. merge objects in array L
},
"$$ROOT"
]
}
}
},
{
$project: { // remove original L array
L: false
}
})
如果您使用的是 v4.2 或更高版本,則可以使用以下略短的語法
db.collection.aggregate({
$replaceWith: {
$mergeObjects: [
{
$mergeObjects: "$L"
},
"$$ROOT"
]
}
},
{
$unset: "L"
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.