• 赚钱入口【需求资源】限时招募流量主、渠道主,站长合作;【合作模式】CPS长期分成,一次推广永久有收益。主动打款,不扣量;

BSON类型的int转换为Date

JavaScript cps12345 1年前 (2020-07-20) 306次浏览 0个评论

问题

我的数据结构:

BSON类型的int转换为Date

基于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

解决方法

将数据从type转换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" }          
        }      
      },   
   ]  
);
喜欢 (0)

您必须 登录 才能发表评论!