【问题标题】:I want to group by month and get sum of amount from project embedded document我想按月分组并从项目嵌入文档中获取金额总和
【发布时间】:2022-01-19 17:03:26
【问题描述】:

这是我的 mongo-DB 数据库集合图像 [1]:https://i.stack.imgur.com/TIKh1.png

我想添加查询,其中我需要按月获取分组以及从嵌入在(usermodel)集合中的(项目)数组中的(数量)总和

这是我目前的做法,但在控制台中没有显示输出

router.get('/calculatedata', Authenticate, async (req, res) => {
    try {
        const getUser = await UserModel.findById({ _id: req.userID });
        const getProject = await getUser.aggregate([
            {$unwind: '$project' },
            {$group: { _id: { month: "$month" },
                      total:{$sum:"$project.amount"}
                     }
            }]);
        console.log(getProject)
    } catch (error) {
        res.status(400).send({ message: "Something Went Wrong" })
    }
})

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

需要先从日期中提取月份,再从字符串中提取日期,例如:

 month: {$month: { $dateFromString:{ dateString:"$project.date" , timezone:'America/New_York' }} }

或从字符串中提取月份类似数字(01..12):

    month: {  $substr: ["$project.date", 5, 7]     }

【讨论】:

  • 但我无法访问项目嵌入文档。
  • 如何实现对项目文档的查询
  • 在 $unwind 项目数组之后,您可以使用“.”访问子文档。如上图,还请提供文本文档示例,以便进一步处理...
猜你喜欢
  • 2020-01-08
  • 2020-07-24
  • 2021-07-20
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多