按当月筛选 mongodb 数据
Filter mongodb data by current month
我尝试在 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
我假设它是一个字符串这一事实实际上是您的插入代码中的一个错误,您应该改为修复它。
我尝试在 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
我假设它是一个字符串这一事实实际上是您的插入代码中的一个错误,您应该改为修复它。