2

我正在尝试根据当前月份的日期在聚合中执行计算。例如,我想将交易总数除以当月的某一天,得到每天的交易。

问题是我不知道如何获取当前日期。我看到很多硬编码的例子,但我需要的是更像 MySQL NOW() 函数。

我试过这样的事情:

> db.statistics.aggregate([{$project: {dayofmonth: {$dayOfMonth: Date()}}}])
{
        "errmsg" : "exception: can't convert from BSON type String to Date",
        "code" : 16006,
        "ok" : 0
}

但这会产生您看到的错误。

如何获取当前月份的当前日期以用于聚合计算?

4

1 回答 1

4

你几乎做到了。你必须写new Date()

db.statistics.aggregate([
    {$project: {dayofmonth: {$dayOfMonth: new Date()}}}
])

它将产生如下结果:

{
    "result" : [ 
        {
            "_id" : "statisctiId",
            "dayofmonth" : 9
        }
}
于 2013-05-09T07:42:53.430 回答