【问题标题】:MongoDB aggregation NumberLong to Date [duplicate]MongoDB聚合NumberLong to Date [重复]
【发布时间】:2016-04-13 06:07:40
【问题描述】:

mongodb的示例文档:

{
    "_id" : ObjectId("512eef329d5d0c9415000025"),
    "time" : NumberLong(1431973102)
}

我想从聚合查询中保存在时间属性中的时间戳值中获取 $dayOfMonth,但我有这个异常消息:

uncaught exception: aggreate failed: {
   "errmsg" : "exception: can't convert from BSON type NumberLong64 to Date",
   "code" : 16006,
   "ok" : 0
}

当我运行这个查询时:

db.getCollection('collection_name').aggregate([
{ $match: { '_id': ObjectId('512eef329d5d0c9415000025') } },
{ $project: { 'time': 1, "dayOfMonth": { $dayOfMonth: '$time' } } }
])

有什么想法吗?谢谢。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您首先需要使用 $add 将 Unix 纪元转换为 ISODate

    db.data.aggregate({
      $project: {
        "dayOfMonth": {
          $dayOfMonth: {
            $add: [new Date("1970-01-01"), {
              $multiply: ["$time", 1000]
            }]
          }
        }
      }
    })
    

    在您的查询中实现这一点:

    db.data.aggregate([
    {$match: { '_id': ObjectId('512eef329d5d0c9415000025') } },
    {$project: {"time": 1,"dayOfMonth": {$dayOfMonth: {$add: [new Date("1970-01-01"), {$multiply: ["$time", 1000]}]}}}}])
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Java,那么我建议您使用 Joda-Time 库将日期转换为纪元并提取所需的月份。

      DateTime date = new DateTime(dateInMilli); 
      date.dayOfMonth();
      

      如果应用程序的任何地方都没有使用日期,那么您也可以将其保存为 ISODate 格式而不是 Epoch。

      如果你使用 JS,那么 JohnnyHK 提供的链接有更多信息。

      【讨论】:

        猜你喜欢
        • 2021-03-31
        • 1970-01-01
        • 2019-02-01
        • 2018-11-17
        • 2019-10-14
        • 2019-11-04
        • 2019-01-15
        • 2019-03-04
        • 1970-01-01
        相关资源
        最近更新 更多