【问题标题】:Can't convert from BSON type int to Date无法从 BSON 类型 int 转换为 Date
【发布时间】:2020-11-09 05:57:03
【问题描述】:

我有这样的集合结构。

我想使用此代码根据 date_created 字段按月份对集合进行分组。

db.activities.aggregate(
   [     
      { $match: { type: "Expense", "user_hash": "xxx" } },     
      {   
        $group: { 
           _id: { month: { $month: "$date_created" } },            
           total: { $sum: "$amount" }          
        }      
      },   
   ]  
); 

我正在处理这个异常。

2020-07-19T23:13:01.652+0700 E  QUERY    [js] uncaught exception: Error: command failed: {
    "operationTime" : Timestamp(1595175178, 1),
    "ok" : 0,
    "errmsg" : "can't convert from BSON type int to Date",
    "code" : 16006,
    "codeName" : "Location16006",
    "$clusterTime" : {
        "clusterTime" : Timestamp(1595175178, 1),
        "signature" : {
            "hash" : BinData(0,"xxx"),
            "keyId" : NumberLong("xxx")
        }
    }
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:583:17
assert.commandWorked@src/mongo/shell/assert.js:673:16
DB.prototype._runAggregate@src/mongo/shell/db.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1012:12
@(shell):1:1

有什么解决办法吗?提前谢谢你。

【问题讨论】:

    标签: javascript mongodb


    【解决方案1】:

    您必须将数据类型从int 转换为Date。您可以使用 $toDate 运算符(可从 MongoDB v4.0 获得)来做到这一点。

    显然您以秒为单位存储时间戳,因此您必须乘以 1000 才能获得以毫秒为单位的时间戳,然后再将其传递给$toDate

    db.activities.aggregate(
       [     
          { $match: { type: "Expense", "user_hash": "xxx" } },     
          {   
            $group: { 
               _id: {
                   month: {
                       $month: { $toDate: { $multiply: ["$date_created", 1000] } }
                   }
               },            
               total: { $sum: "$amount" }          
            }      
          },   
       ]  
    ); 
    

    【讨论】:

    • 感谢@thammada.ts 的明确解释和回答
    猜你喜欢
    • 2013-04-18
    • 2017-04-22
    • 2020-10-23
    • 2017-11-04
    • 2015-04-09
    • 2011-12-27
    • 2017-06-17
    • 2013-01-25
    相关资源
    最近更新 更多