Home > Back-end >  how to add or modify the date in mongo db pipeline through node js
how to add or modify the date in mongo db pipeline through node js

Time:07-29

I have an api in nodejs, which performs mongodb aggregation, in that pipeline the date values will add through request params with the help of an api, aggregation is working fine. but these date values are not getting evaluated.

my nodejs aggregate pipeline:

const result = await db.collection.aggregate(
  {
    "$match": {
      "TaskCompletedDate": { "$gte": "new Date(`${req.query.startDate}`)", "$lt":"new Date(`${req.query.endDate}`)" }
    }
  },
  {
    "$group": {
      "_id":{
        "ProductTypeCode":"$ProductTypeCode"
      },
      "count": { "$sum": 1 }
    }
  },
  {
    "$project": {
      "_id":0,
      "concat":{ "$concat": [{ "$toString": "$count" }, "$_id.ProductTypeCode"] }
    }
  }
]).toArray();

Passing startDate and endDate through API like this: http://localhost:3000/stored_procedure/HRC_getTaskCompletedCountPerProduct?startDate="2022-01-12T00:00:00.0Z"&endDate="2022-01-23T00:00:00.0Z"

The aggregation is working fine. But I am not able to see output when I am passing dates like mentioned above. Can anyone please help me on this

CodePudding user response:

{$match: { "TaskCompletedDate": { $gte: req.query.startDate, $lte: req.query.endDate}}},

CodePudding user response:

"new Date(`${req.query.startDate}`)"

is evaluated as a literal string. You cannot use JavaScript's backticks for string substitution inside double-quotes.

Try using

[
 {
    "$match": {
      "TaskCompletedDate": { "$gte": new Date(`${req.query.startDate}`), "$lt": new Date(`${req.query.endDate}`) }
    }
  },
  {
    "$group": {
      "_id":{
        "ProductTypeCode":"$ProductTypeCode"
      },
      "count": { "$sum": 1 }
    }
  },
  {
    "$project": {
      "_id":0,
      "concat":{ "$concat": [{ "$toString": "$count" }, "$_id.ProductTypeCode"] }
    }
  }
]

If the dates are stored as strings (not actual date objects) in Mongo, then use:

new Date(`${req.query.startDate}`).toISOString()
  • Related