Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
retrieve all whose `date` is within last 6 minutes

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.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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
        }
  })
over 4 years ago · Santiago Trujillo Denunciar

0

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
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda