按当月筛选mongodb数据



我尝试在mongodb、中按月查询find

我收集的数据是这样的:

"   
_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

我认为它是一个字符串的事实实际上是插入代码中的一个错误,您可能应该修复它。

最新更新