Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

705
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!