我有以下架構,我在 JS 中使用帶有貓鼬的聚合框架
{
id: 1,
name: Alfred,
age: 10,
orders:[
{type:"A",address:"Address1"},
{type:"A",address:"Address2"},
{type:"B",address:"Address4"},
{type:"B",address:"Address5"},
{type:"B",address:"Address6"},
...
]
},
{
id: 2,
name: Bren,
age: 15,
orders:[
{type:"B",address:"Address1"},
{type:"B",address:"Address2"},
{type:"B",address:"Address4"},
{type:"A",address:"Address5"},
{type:"B",address:"Address6"},
...
]
}
我正在嘗試獲得此輸出
{
id: 1,
name: Alfred,
age:10,
countTypeA:2,
countTypeB:3
},
{
id: 2
name: Bren,
age: 15,
countTypeA: 1,
countTypeB: 4
}
我試過使用$unwind,$group:{_id:"orders.type"}但我丟失了每一行的原始資料(姓名、年齡),我不介意丟失地址資訊,我有興趣計算每個用戶在他們的訂單串列中的訂單型別.
uj5u.com熱心網友回復:
$unwindorders-將陣列解構為多個檔案。$groupid- 按和分組orders.type。并通過 存盤其他屬性$first。$group- 分組id。通過 存盤其他屬性$first。type并使用鍵值對檔案創建陣列。$replaceRoot- 將輸入檔案替換為所需檔案。$unset- 洗掉type欄位。
db.collection.aggregate([
{
$unwind: "$orders"
},
{
$group: {
_id: {
id: "$id",
type: "$orders.type"
},
name: {
$first: "$name"
},
age: {
$first: "$age"
},
count: {
$sum: 1
}
}
},
{
$group: {
_id: "$_id.id",
name: {
$first: "$name"
},
age: {
$first: "$age"
},
type: {
$push: {
k: {
$concat: [
"countType",
"$_id.type"
]
},
v: "$count"
}
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$$ROOT",
{
"$arrayToObject": "$type"
}
]
}
}
},
{
$unset: "type"
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430450.html
