Search code examples
mongodbmongoosemongodb-querymongoose-populate

In MongoDB, how to ignore documents that was inserted less than five minutes of time from the time of fetching


testResults.aggregate([
  { $match: { testId: { "$exists": true } } },
  { $sort: { _id: -1 } },
  {
    $group: {
      _id: "$testId",
      testDetails: {
        $push: {
          result: "$result",
          testName: "$testName"
        }
      }
    }
  },
  {
    $addFields: {
      testDetails: { $slice: ["$testDetails", 30] }
    }
  }
])
.exec(function (err, testResults) {
  if (err) res.send(err);
  res.json(testResults);
});

Using this aggregate method, I am fetching recent 30 documents. Now, I need to ignore documents that was inserted less than five minutes of time from the time of fetching. In, $match aggregate how to achieve this or is there any other way?


Solution

  • A $match stage like this should do:

    {
      $match: {
        $expr: {
          $lt: [
            {$toDate: '$_id'},
            {$subtract: [new Date(), 300000]}
          ]
        }
      }
    }
    

    The 300000 is 5 minutes in milliseconds.