Sometimes, we want to query MongoDB ObjectId by date with JavaScript.
In this article, we’ll look at how to query MongoDB ObjectId by date with JavaScript.
How to query MongoDB ObjectId by date with JavaScript?
To query MongoDB ObjectId by date with JavaScript, we call the ObjectId.fromDate
method.
For instance, we write
db.users.find({
_id: { $lt: ObjectId.fromDate(new ISODate("2022-01-05T00:00:00.000Z")) },
});
to call find
to find the users
entries that has object ID less than the given date.
We call ObjectId.fromDate
to convert the ISODate
to an object ID.
Conclusion
To query MongoDB ObjectId by date with JavaScript, we call the ObjectId.fromDate
method.