如何在mongodb获得特定月份的日记录?

时间:2016-06-29 11:19:46

标签: node.js mongodb mongoose aggregation-framework

这是我的架构

empname: {type: String},
soldby: {type: String},
expenseprice:{type:Number},
expensedesc:{type:String},
expensetype:{type:String},
createdat: {type: Date, default: Date.now}

我试过了这个查询

db.expenses.aggregate([
    {
        $project: {
            _id: 1,
            year: { $year: "$createdat" },
            month: { $month: "$createdat" },
            day: { $dayOfMonth: "$createdat" },
            expenseprice: 1
        }
    },
    {
        $group: {
           _id: {
              year: "$year",
              month: "$month",
              day: "$day"
           },
           sum: { $sum: "$expenseprice" }
        }
    }
])

我的输出为

{ "_id" : { "year" : 2015, "month" : 8, "day" : 15 }, "sum" : 200 }
{ "_id" : { "year" : 2016, "month" : 5, "day" : 20 }, "sum" : 150 }
{ "_id" : { "year" : 2016, "month" : 6, "day" : 29 }, "sum" : 250 }

我只想要特定年份和特定月份的记录,并且在那个月,明天就像这样

{ "_id" : { "year" : 2016, "month" : 6, "day" : 28 }, "sum" : 150 }
{ "_id" : { "year" : 2016, "month" : 6, "day" : 29 }, "sum" : 200 }

我也试过了$match

db.expenses.aggregate([
    {
        $project: {
            _id: 1,
            year: { $year: "$createdat" },
            month: { $month: "$createdat" },
            day: { $dayOfMonth: "$createdat" },
            expenseprice: 1
        }
    },
    {
        $match: {
            $eq: ["$month", 06]
        }
    },
    {
        $group: {
            _id: {
                year: "$year",
                month: "$month",
                day: "$day"
            },
            sum: { $sum: "$expenseprice" }
        }
    }
])

但是我收到了这样的错误

assert: command failed: {
    "ok" : 0,
    "errmsg" : "bad query: BadValue unknown top level operator: $eq",
    "code" : 16810
} : aggregate failed
_getErrorWithCode@src/mongo/shell/utils.js:23:13
doassert@src/mongo/shell/assert.js:13:14
assert.commandWorked@src/mongo/shell/assert.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1215:5
@(shell):1:1

2016-06-29T16:20:47.754+0530 E QUERY    [thread1] Error: command failed: {
    "ok" : 0,
    "errmsg" : "bad query: BadValue unknown top level operator: $eq",
    "code" : 16810
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:23:13
doassert@src/mongo/shell/assert.js:13:14
assert.commandWorked@src/mongo/shell/assert.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1215:5
@(shell):1:1

1 个答案:

答案 0 :(得分:1)

请参阅以下示例,了解如何引用$ group中的年份和月份。根据我的理解,这是您需要的最后一点。

db.expenses.aggregate([
   {$project: {_id:1,year:{$year:"$createdat"},month:{$month:"$createdat"}, day:{$dayOfMonth:"$createdat"},expenseprice:1}},
   {$group: {_id:{year:"$year",month:"$month",day:"$day"}, sum:{$sum:"$expenseprice"}}},
   {$match : {"_id.year" : 2016, "_id.month" : 6}}])

我不确定你为什么在赛后添加了另一组。从我最初的理解,可能不需要。如果上述解决方案不符合预期,请更新评论或要求。我会相应地调整答案。

我用一些示例数据测试了我的查询。数据被过滤了一个月,我得到明天的分解。