$ /tutorials

MongoDB Query date by _id field

published · 1 minute read · mongodb query
MongoDB Query date by _id field

In order to make a query based on _id, comparing dates, you can use $convert function to extract the date from ObjectId.

Example:

$convert: { input: "$_id", to: "date" } 

To query dates comparing between start and end time:

db.collection.find({
  "$expr":{
    "$and":[
      {"$gte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2023-08-01T00:00:00.000Z")]},
      {"$lte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2023-08-02T11:59:59.999Z")]}
    ]
  }
})

The shorthand version using $toDate function helps you achieve the same result:

db.collection.find({
  "$expr":{
    "$and":[
      {"$gte":[{"$toDate":"$_id"}, ISODate("2023-08-01T00:00:00.000Z")]},
      {"$lte":[{"$toDate":"$_id"},ISODate("2023-08-02T11:59:59.999Z")]}
    ]
  }
})

Source

Image by Vikash Kr Singh from Pixabay