I have a collections like this:
{
"_id" : ObjectId("963fae9d93f4d930c98e269d"),
"myDate":ISODate("2017-02-05T05:00:00.000Z"),
"otherData":"blablabla"
},
{
"_id" : ObjectId("963fae9d93f4d930c98e269d"),
"myDate":ISODate("2017-02-05T14:00:00.000Z"),
"otherData":"blablabla"
},
{
"_id" : ObjectId("963fae9d93f4d930c98e269d"),
"myDate":ISODate("2017-03-05T02:00:00.000Z"),
"otherData":"blablabla"
},
{
"_id" : ObjectId("963fae9d93f4d930c98e269d"),
"myDate":ISODate("2017-03-05T19:00:00.000Z"),
"otherData":"blablabla"
}
Given the current date (with minutes and seconds), I want to find the record nearest to the current date (by the "myDate" field).
Thanks
$currentDate sets the specified field to the date when $currentDate was run. If the field does not exist, $currentDate adds the field to a document. Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $currentDate with an empty operand expression ( { } ).
Comparison Based on Date in MongoDB First, create a collection called 'data' using the document to further understand the concept. Use the find() function to show all the documents in a collection. The following is the date-based return query. Records with a creation date after 2018-05-19T11:10:23Z will be returned.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.
You can subtract the dates in your collection with current date, take the absolute value of the difference to consider for future date and then use sort and limit to get the nearest document:
db.a.aggregate([
{
$project : {
myDate : 1,
otherData : 1,
difference : {
$abs : {
$subtract : [new Date(), "$myDate"]
}
}
}
},
{
$sort : {difference : 1}
},
{
$limit : 1
}
])
You can use an additional $project
if you want the difference
field in the output document. Also instead of current date you can use any other date and find the nearest date to that date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With