retrieve all whose `date` is within last 6 minutes

Viewed 143

I have a Product collection stored in MongoDB. It has a attribute date :

const productSchema = new mongoose.Schema<ProductAttrs>({
    date: {
        type: Date, 
        required: true,
    }
    ...
})

I would like to retrieve all products whose date is within last 6 minutes comparing with current time. What is the efficient way to retrieve that in mongoose ?

I am using express.js + typescript + mongoose v5.11 in my project.

2 Answers

You must use Mongoose to search every record where the time is greater than now - 6 minutes.
I have no way to test it, but the query should look something like this:

const sixMinutes = (6*60*1000); // 6 minutes
let sixMinutesAgo = new Date();
sixMinutesAgo.setTime(sixMinutesAgo.getTime() - sixMinutes);

const products = Product.find({ 
  date: {
        $gte: sixMinutesAgo
        }
  })

If your MongoDB server version is 5.0 you could use the new operator $dateDiff. In this case it is very handy and you do not even need an aggregate:

db.collection.find({
  "$expr": {
    "$lte": [
      {
        "$dateDiff": {
          startDate: "$date",
          endDate: new Date(),
          unit: "minute"
        }
      },
      6
    ]
  }
})

It allows you to specify the unit field, which makes the query very straightforward in my opinion.

$expr evaluates an expression and returns true or false, just that. If the expression result is true then the row is returned, otherwise it is not.

$lte means less than or equal (the <= operator) and it returns true only when the first argument is less than or equal the second operator. Basically, this is what it does in pseudocode:

foreach doc in collection
    if (minute)(currentDate - document.date) <= 6 then
        return document
Related