javascript - 无法从 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" }
}
},
]
);
推荐阅读
- ios - 如何将可移动资产添加到 iOS 应用程序
- android - 工人类上的 ClassNotFoundException
- sql-server - SQL Server 2017 MLS 和 pip - 无法卸载
: “这是一个 distutils 安装的项目” - oracle-nosql - 如何获得有关 Oracle NoSQL 管理计划的反馈
- flutter - 颤振 | 从最顶部的屏幕更新导航器堆栈中所有屏幕上的复选框
- pyspark - 在 PySpark 中读取两个具有不同身份验证令牌的文件
- sql - BigQuery - 使用字符串和数组加入两个表
- faunadb - 如何将 q.Now() 结果转换为动物群中的字符串
- mongodb - 如何获取名称中带有空格字符的集合的信息?
- php - cURL 无法使用 PHP 连接,但可以通过 IDE 连接