我有一个使用本机mongodb驱动程序来处理数据的Node / Express后端。我有以下功能可从mongodb数据库中提取数据:
else if (year && grouping == 2){
collection.aggregate([
{ $match: {postdate: { $gte : new Date(yearstart), $lte : new Date(yearend)},factor:1 }},
{ $group: { _id: {"category":"$category","month":{ "$month": "$postdate" }} , "total": { $sum: "$debit" } } },
{ $project: { "_id":0, "category":"$_id.category", "month":"$_id.month", "total":1 } }
]
).toArray(function(err, items) {
console.log("get transactions by year and month category grouping result: ", items);
res.json(GroupByMonthCat(items));
}
yearstart的值是:'2018-01-01',yearend的值是'2018-12-01'。因此,在我的查询中,我将匹配的记录分组为postdate的月份。
但是,我得到的结果如下(类别:账单和月份:1):
{
"subtotal" : 475,
"category" : "Bills",
"month" : 1
}
当我直接在我的应用程序外部针对mongodb运行相同的查询时:
db.transtest.aggregate(
[
{ $match: {category: "Bills" ,postdate: { $gte : new Date("2018-01-01"), $lte : new Date("2018-01-31")},factor:1 }},
{ $group: { _id: {"category":"$category","month":{ "$month": "$postdate" }} , "subtotal": { $sum: "$debit" } } },
{ $project: { "_id":0, "category":"$_id.category", "month":"$_id.month", "subtotal":1} },
{ $sort : { category : -1, month: 1 } }
]
);
我得到以下结果:
{
"subtotal" : 183.9,
"category" : "Bills",
"month" : 1
}
为什么会这样?在2018年1月的数据库中只有两个结果,因此当我直接对数据库运行相同的确切查询时,我的预期小计为183.9:
{
"_id" : ObjectId("5a7641b0d4b6828ad37c99a1"),
"transid" : 5500,
"postdate" : ISODate("2018-01-16T05:00:00.000Z"),
"category" : "Bills",
"debit" : 53.9
},
{
"_id" : ObjectId("5a7641b0d4b6828ad37c99a5"),
"transid" : 5504,
"postdate" : ISODate("2018-01-25T05:00:00.000Z"),
"category" : "Bills",
"debit" : 130
}