DEV Community

Bogdan Alexandru Militaru
Bogdan Alexandru Militaru

Posted on • Originally published at whyboobo.com on

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

Enter fullscreen mode Exit fullscreen mode

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")]}
    ]
  }
})

Enter fullscreen mode Exit fullscreen mode

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")]}
    ]
  }
})

Enter fullscreen mode Exit fullscreen mode

Source

Image by Vikash Kr Singh from Pixabay

Top comments (0)