首页 > 解决方案 > 无法从 BSON 类型 int 转换为 Date

问题描述

我有一个集合的这种结构。 MongoDB结构

我想使用此代码根据 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

有什么解决办法吗?先感谢您。

标签: javascriptmongodb

解决方案


您必须将数据从 type 转换intDate. 您可以使用$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" }          
        }      
      },   
   ]  
); 

推荐阅读