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

707
Visualizações
mongodb compass query with objectId in date range

I'm trying to perform a date range query on the _id field using compass. I've tried what I found here with the following filter:

{_id: { $gte: ObjectId.fromDate(new Date('2019-01-01')) } }

What am I missing? I'd like to get a list of all documents from some date forward (in this example from 1 Jan 2019 to present). Unfortunately there isn't a timestamp in the document fields so I need to extract it from the object id.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to pass a date object to the ObjectId.fromDate, not a string. Try this:

ObjectId.fromDate(new Date('2019-01-01'))

This function works only in the shell and doesn't exist in the drivers.

EDIT after comments:

Here is a solution that works in Compass as well:

{ 
    $expr: { 
        $gte: [
            {"$toDate":"$_id"}, 
            ISODate("2021-01-01T00:00:00.000Z") 
        ]
    } 
}

Keep in mind, however, that it requires a version of mongo of 4.0+. You can checkout the docs here.

Also, checkout this related topic: Can I query MongoDB ObjectId by date?

It is not about Compass, but it provides solutions for generating the ObjectIds from a date without being dependent on ObjectId.fromDate().

over 4 years ago · Santiago Trujillo Relatório

0

I found a solution, maybe not the best but it does the job. Hopefully this can help someone with the same problem if there isn't a cleaner solution.

I converted the date I needed to an ObjectId outside of compass online here. Then I wrote the query with that ObjectId:

{_id: { $gte: ObjectId(' object id here ') } }

As suggested in the comments, see this related topic. It's not specific to Compass but it provides a solution for generating ObjectIds from a date without being dependent on ObjectId.fromDate().

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