How to search date range in aggregate

Hello, I’m trying to make a request for my forum, I’ve worked with date for the schema.find without problem but can’t make it work with aggregate, can someone help me please ?

//Get Post Number By Category and range of Day
module.exports.postCatDate_GET = async (req, res) => {
    const day = parseInt(req.query.day); // ?day=100
    try {
        var posts = await Post.aggregate([{ 
            createdAt: {
                "$gte": ISODate(new Date(new Date() - day * 60 * 60 * 24 * 1000)),
            },
            "$group": {
                _id: "$categoryId",
                count: {
                    $sum: 1
                }
            }
        }])

        res.status(200).json(posts);
    } catch (err) {
        res.status(500).json(err);
    }
}

The group part work but I can’t add the date search like in find, I’ve read a lot about ISODate but keep the internal error.

Hello @Virgil_Nauleau, Welcome to the MongoDB Community forum!

First, there are syntax errors in your aggregation pipeline. Each stage is to be within a set of braces { ... }. And, each stage has a stage name like, $match, $group, $project, etc.

You define stages like this and build the pipeline, and then run the query:

var match_stage = {
    $match: { 
        createdAt: { $gte: { .... } } 
    }
}

var group_stage = {
    $group: {
        _id: "$categoryId",
        count: { $sum: 1 }
    }
}

var pipeline = [ match_stage, group_stage ]
var posts = await Post.aggregate(pipeline)
// ... rest of your code here

Reference:

3 Likes

Hi,

You should use the $match stage to match documents, and $group stage to group them:

db.orders.aggregate([
  {
    "$match": {
      "createdAt": {
        "$gte": ISODate(new Date(new Date() - day * 60 * 60 * 24 * 1000))
      }     
    }
  },
  {
    "$group": {
      "_id": "$categoryId",
      "count": {
        "$sum": 1
      }
    }
  }
])
1 Like

Thank you so much !!! T.T It perfectly work, kinda remind me Prepare table of sqlite using Golang
I think I will make var like that more often for my agregate

2 Likes

I tryed it like that but didnt worked, maybe because of the .orders that ive never saw before (for the rest ive tryed exactly the same

Also why using ISODate while it work the same with just “new Date()” ?

ISODate is same as that of the Date in mongosh.

I am working with Node.js and I also use new Date() in queries. I copied ISODate() from the question.

At first i though it was a necessary cast because everyone does it (from forum I’ve seen from my problem) but resulting in changing absolutely nothing that’s why I was asking

Folks, when working with a NodeJS application (using MongoDB NodeJS Driver or Mongoose ODM), use the JavaScript Date. ISODate is for mongo shell (see my previous comment links).

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.