首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将聚合用于模型?

如何将聚合用于模型?
EN

Stack Overflow用户
提问于 2022-04-08 08:28:13
回答 1查看 30关注 0票数 1

我有一个名为Course的模型,如下所示,其中有一个模型(嵌入):

代码语言:javascript
运行
复制
{
    "_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"
}

模型类似于:

代码语言:javascript
运行
复制
{
    "_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",        
}

这是我的两个模型,课程和章节非常大,我在这里写,但是这个信息对所有的人来说都是可以的。所以,我想从输出中得到:

代码语言:javascript
运行
复制
{
    "_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是区段数之和。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-08 08:34:18

代码语言:javascript
运行
复制
db.Course.aggregate([
  {
    $lookup: {
      from: "Section",
      localField: "sections",
      foreignField: "_id",
      as: "sections"
    }
  },
  {
    $set: {
      sumPrice: {
        $sum: "$sections.price"
      },
      numSection: {
        $size: "$sections"
      }
    }
  },
  {
    $unset: "sections"
  }
])

蒙古操场

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71793922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档