Search code examples
javascriptnode.jsmongodb-querymongodate

Filter mongodb data by current month


i try to query find by month in mongodb,

my data in Daq collection is like this:

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

this is my queries:

let n = moment().month()

let test = await Daq.aggregate([
    {$addFields: {  "month" : {$month: '$sampledate'}}},
    {$match: { month: n}}
]);

i already try this too :

let n = moment().month()

let test = await Daq.aggregate([
  {$project: { "month" : {$month: '$sampledate'}}},
  {$match: { month: n}}
]);

but the result is always

"message": "can't convert from BSON type string to Date"

how you guys can solve this?


Solution

  • Your sampledate is not saved as a date object but rather as a string. You first need to convert it to a date and then you can use functions such as $month.

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

    https://mongoplayground.net/p/XOdfYtEXqLc

    I assume the fact that it's a string is actually a bug in your insert code and you should probably fix that instead.