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

706
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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