【问题标题】:MongoDb : Failed to optimize pipeline : caused by : can't convert from BSON type javascript to DateMongoDb:无法优化管道:原因:无法从 BSON 类型 javascript 转换为 Date
【发布时间】:2020-10-23 02:25:29
【问题描述】:

我在 Mongo 中有以下数据,并尝试按天对搜索进行分组。所以我知道每天发生多少次搜索

{
    "_id" : ObjectId("5ee3ebb8a18fae0001cdf0c6"),
    "term" : "wp-login.php",
    "Date" : ISODate("2020-06-12T20:55:20.335Z")
}

我有以下问题

db.search.aggregate(
  {
    $project: {
      year: {$year: Date},
      month: {$month: Date},
      dayOfMonth: {$dayOfMonth: Date}
    }
  },
  {
    $group: {
      _id: {
        year: '$year',
        month: '$month',
        dayOfMonth: '$dayOfMonth'
      },
      count: {
        $sum: 1
      }
    }
  }
)

我收到以下错误

执行脚本失败。

错误:命令失败:{“ok”:0,“errmsg”:“优化失败 管道 :: 导致 :: 无法从 BSON 类型的 javascript 转换为 日期”,“代码”:16006,“代码名称”:“Location16006”}:聚合 失败详情: _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:534:17 assert.commandWorked@src/mongo/shell/assert.js:618:16 DB.prototype._runAggregate@src/mongo/shell/db.js:260:9 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12 DBCollection.prototype.aggregate@:1:355 @(shell):1:1

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    使用 "$Date" 代替 日期

    db.collection.aggregate({
      $project: {
        year: {
          $year: "$Date"
        },
        month: {
          $month: "$Date"
        },
        dayOfMonth: {
          $dayOfMonth: "$Date"
        }
      }
    },
    {
      $group: {
        _id: {
          year: "$year",
          month: "$month",
          dayOfMonth: "$dayOfMonth"
        },
        count: {
          $sum: 1
        }
      }
    })
    

    你可以参考例子here

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 2017-04-22
      • 2020-11-09
      • 2017-09-23
      • 2018-03-20
      • 2018-05-24
      • 2021-10-31
      • 2017-11-04
      • 2015-04-09
      相关资源
      最近更新 更多