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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay