【发布时间】: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