如何在mongodb中获得特定月份的明智记录



这是我的schema

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

I tried this query

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 }

I tried $match too

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

$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}}])

我不知道你为什么在比赛后添加了另一个组。从我最初的理解来看,这可能不是必需的。如果上述解决方案不符合预期,请更新意见或要求。我将相应地调整答案。

我已经用一些样本数据测试了我的查询。数据被过滤了一个月,我得到了按天划分的数据

相关内容

  • 没有找到相关文章

最新更新