You can subtract the dates in your collection with the current date, accept the absolute value of the difference for consideration at a future date, and then use sorting and restriction to get the closest document:
db.a.aggregate([
{
$project : {
myDate : 1,
otherData : 1,
difference : {
$abs : {
$subtract : [new Date(), "$myDate"]
}
}
}
},
{
$sort : {difference : 1}
},
{
$limit : 1
}
])
You can use optional $projectif you want to use the field differencein the output. Also, instead of the current date, you can use any other date and find the closest date to this date.
source
share