mongodbmongodb-compass

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.


Solution

  • 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().