我有一个名为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"
}节模型类似于:
{
"_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是区段数之和。
发布于 2022-04-08 08:34:18
db.Course.aggregate([
{
$lookup: {
from: "Section",
localField: "sections",
foreignField: "_id",
as: "sections"
}
},
{
$set: {
sumPrice: {
$sum: "$sections.price"
},
numSection: {
$size: "$sections"
}
}
},
{
$unset: "sections"
}
])https://stackoverflow.com/questions/71793922
复制相似问题