首页 > 解决方案 > 按当月过滤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"

你们怎么能解决这个问题?

标签: javascriptnode.jsmongodb-querymongodate

解决方案


sampledate的不是保存为日期对象,而是保存为字符串。您首先需要将其转换为日期,然后您可以使用诸如$month.

  $addFields: {
    "month": {
      $month: {
        $toDate: "$sampledate"
      }
    }
  }

https://mongoplayground.net/p/XOdfYtEXqLc

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


推荐阅读