【问题标题】:MongoDB how to filter by two fields(id and month) and also return a sum by all the filtered documents?MongoDB如何按两个字段(id和月份)过滤并返回所有过滤文档的总和?
【发布时间】:2020-02-18 05:54:54
【问题描述】:

您好,我正在编写一个 Node/Express 端点,我正在尝试使用 Mongoose 编写一个 MongoDB 查询,以返回在当前日期或月份内到期的文档的总和值。

目前,我只是想返回当天的总和。

  • 首先我要匹配所有包含用户 ID 的文档。
  • 然后我想匹配当天的所有文档。
  • 最后,我想为所有这些返回 $amount 字段的总和 文件。

我知道这个语法是错误的,我很难找到与我正在做的事情相匹配的好例子。

let now = Date.now(),
    oneDay = 1000 * 60 * 60 * 24,
    today = new Date(now - (now % oneDay)),
    tomorrow = new Date(today.valueOf() + oneDay);

router.get("/user_current_month/:id", [jsonParser, jwtAuth], (req, res) => {
    return Expense.aggregate([
        {
            $match: { user: new mongoose.Types.ObjectId(req.params.id) }
        },
        {
            $match: {
                $expiration: {
                    $gte: today,
                    $lt: tomorrow
                }
            }
        },
        {
            $group: {
                _id: "$month",
                total: {
                    $sum: "$amount"
                }
            }
        }
    ])
        .then(sum => {
            res.status(200).json(sum);
        })
        .catch(err => res.status(500).json({ message: "Something went terribly wrong!" }));
});

这是一个文档的样子:

{
    "_id": {
        "$oid": "5daea018b3d92643fc2c8e6c"
    },
    "user": {
        "$oid": "5d9929f065ef083d2cdbf66c"
    },
    "expense": "Post 1",
    "expenseType": "One Time",
    "notes": "",
    "amount": {
        "$numberDecimal": "100"
    },
    "expiration": {
        "$date": "2019-10-22T06:22:01.628Z"
    },
    "status": "Active",
    "createdAt": {
        "$date": "2019-10-22T06:22:16.644Z"
    },
    "__v": 0
}

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您需要在 AND 子句中传递两个匹配表达式,然后进行分组以执行加法运算。你需要做这样的事情:

    Expense.aggregate([
        { $match: { $and: [{ user: new mongoose.Types.ObjectId(req.params.id) },
       {
                    $expiration: {
                        $gte: today,
                        $lt: tomorrow
                    }
                } ]}},
        { $group: {
                _id: "$month",
                total: {
                    $sum: "$amount"
                }
            }}
        ]);
    

    【讨论】:

    • 我在运行回调函数来记录结果时收到MongoError: unknown top level operator: $expiration。有什么想法吗?
    • 没关系,我明白了,在到期时删除了 $。谢谢。
    • 抱歉这里的错字!
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2020-06-23
    • 2019-01-07
    • 1970-01-01
    • 2014-09-11
    • 2021-01-21
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多