Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda