我有一個名為Course的模型,如下所示,其中有一個截面模型(嵌入):
{
"_id": "624e8e6a870036ee6376d675",
"standardCode": "21321 JH 123",
"name": "JS programming bootcamp",
"description": "",
"start_date": "4/9/2022",
"picture": "course-135526.jpg",
"sections": [
"624e8eb9870036ee6376d690",
"624eda279290d7d518de58a9",
"624ee9a51fbdb9c1986134dd"
]
"createAt": "Thu - 4/8/2022"
},
{
"_id": "624e8e6a870036fd3276d213",
"standardCode": "232 ab 333",
"name": "React programming bootcamp",
"description": "",
"start_date": "4/9/2022",
"picture": "course-135526.jpg",
"sections": []
"createAt": "Thu - 4/8/2022"
}
而Section模型就像:
{
"_id": "624e8eb9870036ee6376d690",
"name": "intro",
"description": "",
"price": 0,
"type": "classroom",
},
{
"_id": "624eda279290d7d518de58a9",
"name": "about js",
"description": "",
"price": 25000,
"type": "classroom",
},
{
"_id": "624ee9a51fbdb9c1986134dd",
"name": "define variable",
"description": "",
"price": 30000,
"type": "classroom",
}
這就是我的兩個模型,我在這里寫的課程和部分非常大,但是這個資訊對所有人來說都可以。所以,我想從輸出中得到這個:
{
"_id": "624e8e6a870036fd3276d213",
"sumPrice": 0,
"numSection": 0,
"standardCode": "232 ab 333",
"name": "React programming bootcamp",
"description": "",
"start_date": "4/9/2022",
"picture": "course-135526.jpg",
"createAt": "Thu - 4/8/2022"
},
{
"_id": "624e8e6a870036ee6376d675",
"sumPrice": 55000,
"numSection": 3,
"standardCode": "21321 JH 123",
"name": "JS programming bootcamp",
"description": "",
"start_date": "4/9/2022",
"picture": "course-135526.jpg",
"createAt": "Thu - 4/8/2022"
}
其中SumPrice是部分價格的總和,numSection是部分數量的總和。
uj5u.com熱心網友回復:
db.Course.aggregate([
{
$lookup: {
from: "Section",
localField: "sections",
foreignField: "_id",
as: "sections"
}
},
{
$set: {
sumPrice: {
$sum: "$sections.price"
},
numSection: {
$size: "$sections"
}
}
},
{
$unset: "sections"
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457731.html
上一篇:Nodejs分頁的一個錯誤
