javascript - 按当月过滤mongodb数据
问题描述
我尝试在mongodb中按月查询查找,
我在 Daq 集合中的数据是这样的:
"
_id" : ObjectId("5f14081c14c08a261b816d57"),
"battery_voltage" : 3673,
"total_usage" : 0.483,
"signal" : 14,
"samplehour" : "2020-07-18T23:59:59-04:00",
"sampledate" : "2020-07-18T23:59:59-04:00",
这是我的查询:
let n = moment().month()
let test = await Daq.aggregate([
{$addFields: { "month" : {$month: '$sampledate'}}},
{$match: { month: n}}
]);
我也已经尝试过了:
let n = moment().month()
let test = await Daq.aggregate([
{$project: { "month" : {$month: '$sampledate'}}},
{$match: { month: n}}
]);
但结果总是
"message": "can't convert from BSON type string to Date"
你们怎么能解决这个问题?
解决方案
您sampledate
的不是保存为日期对象,而是保存为字符串。您首先需要将其转换为日期,然后您可以使用诸如$month
.
$addFields: {
"month": {
$month: {
$toDate: "$sampledate"
}
}
}
https://mongoplayground.net/p/XOdfYtEXqLc
我认为它是一个字符串的事实实际上是您插入代码中的一个错误,您可能应该修复它。
推荐阅读
- python - 使用 Pandas 为大型数据集计算/添加新列的更有效方法
- pandas - 如何将数据框导出回我从中导入的原始 csv 文件?
- java - Java 过滤器空指针
- wso2 - 更新 API 定义时出现 WSO2 APIM 3.2.0 错误
- python - 相机校准,焦距值似乎太大
- processing - 如何在处理中旋转按钮
- typescript - 简化字典的声明,其中键的值是字符串的属性名称
- java - 在 Java SDK 中模拟 Azure 存储 Blob
- c# - 如何在 C# 中使用预处理器指令在 Windows 10 上执行一些代码?
- angular - 使用来自 ASP.Net Core 的服务器端数据初始化 Angular