樣本資料
預期輸出:
[
{
"_id": "healty",
"doc_count": 2,
"ingredients": {
"Leaves": {
"1.2g": 1,
"1.5g": 1
},
"Spinach": {
"12g": 1,
"18g": 1
}
}
},
{
"_id": "junk",
"doc_count": 3,
"ingredients": {
"cheese": {
"100g": 1,
"120g": 2
},
"meat": {
"50g": 1,
"60g": 1,
"70g": 1
}
}
}
]
下面的聚合:操場1
db.collection.aggregate([
{
$group: {
"_id": "$type", // grouping the document by "type" field
"ingredients": {
$push: "$$ROOT" //want to run Playground2 aggrgtion in each of it
},
"doc_count": {
$sum: 1 // total count
}
}
}
])
在那之后,
我還想出了一個轉換成分陣列的另一個步驟: Playground 2
但是,此聚合適用于所有檔案。我想讓Playground2聚合僅適用于每個組物件中的成分欄位。
它類似于結合Playground1和Playground2。我該怎么做呢?
uj5u.com熱心網友回復:
db.collection.aggregate([
{
"$set": {
"ingredients": {
"$objectToArray": "$ingredients"
}
}
},
{
"$unwind": "$ingredients"
},
{
"$group": {
"_id": {
type: "$type",
ingredient: "$ingredients"
},
"count": {
"$sum": 1
},
"doc_count": {
"$addToSet": "$item"
}
}
},
{
"$group": {
"_id": {
type: "$_id.type",
ingredient: "$_id.ingredient.k"
},
"docs": {
"$push": {
k: "$_id.ingredient.v",
v: "$count"
}
},
"doc_count": {
"$push": "$doc_count"
}
}
},
{
"$group": {
"_id": "$_id.type",
"ingredients": {
"$push": {
k: "$_id.ingredient",
v: {
"$arrayToObject": "$docs"
}
}
},
"doc_count": {
"$push": {
$reduce: {
input: "$doc_count",
initialValue: [],
in: {
$concatArrays: [
"$$value",
"$$this"
]
}
}
}
}
}
},
{
"$set": {
"ingredients": {
"$arrayToObject": "$ingredients"
},
doc_count: {
"$size": {
"$setUnion": {
$reduce: {
input: "$doc_count",
initialValue: [],
in: {
$concatArrays: [
"$$value",
"$$this"
]
}
}
}
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432875.html
標籤:javascript 数组 mongodb 目的 聚合框架
