0

I have below code which is working fine and displaying 100 records descending order of Vote value from MongoDB collection;

var myAggregate = Entry.aggregate([{ $group: { _id: "$url",author: { $first: "$author" }, vote: { $max: "$vote" }, url: { $first: "$url" }, title: { $first: "$title" } } },{ $sort:{ vote:-1} },{ $limit: 100 }]);

// Home Route
app.get('/', function(req, res) {
  myAggregate.exec(function(err, entries) {
      if (err) {
          console.log(err)
      } else {
          res.render('index', {
              entries: entries
          });
      }
  });
});

What i am trying to achieve is to filter this data based on today's date.

My schema looks like this;

{
    "_id": {
        "$oid": "5ec6efe565915b59f10787b4"
    },
    "title": "my title",
    "url": "https://myurl.com",
    "author": "john",
    "created": {
        "$date": "2020-05-22T00:17:14.340Z"
    },
    "vote": 51
}

My index page should display 100 records which are created today.

So for example if my entry is created within Today's date and time range then it should be displayed.

I tried to follow explanation on this question but did not work for me.I am receiving Arguments must be aggregate pipeline operators error. Any idea what i am missing here?

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999); 

var myAggregate = Entry.aggregate([{ $group: { _id: "$url",author: { $first: "$author" }, vote: { $max: "$vote" }, url: { $first: "$url" }, title: { $first: "$title" } } },{ $sort:{ vote:-1} },{created: {$gte: start, $lt: end}},{ $limit: 100 }]);
thatthing
  • 676
  • 3
  • 15
  • 39

1 Answers1

1

Two things to take care:

  1. created is neither an operator in aggregation pipeline nor an operator in MongoDB, I guess.

I assume that, you want to filter documents that fall with in the start and end range, you can replace this

{created: {$gte: start, $lt: end}}

with

{
  $match: {
    $expr: {
      $and: [
        {
          $gte: [
            "$created",
            start
          ]
        },
        {
          $lt: [
            "$created",
            end
          ]
        }
      ]
    }
  }
}
  1. After, carefully going through your query, I saw that you are missing created field in $group stage of your aggregation pipeline. Just add the below:
created: {
  $first: "$created"
}
ngShravil.py
  • 4,742
  • 3
  • 18
  • 30