Mongodb request. How to find the one closest to the current date?

I have such collections:

{
    "_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 (minutes and seconds), I want to find the record closest to the current date (in the "myDate" field).

thank

+4
source share
2 answers

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.

+6
source

, , , , - a second(s), minute(s), hour(s) , day(s) or year(s). , ve current and current + nearest factor myDate

some_collection.find({
    myDate: {
        $gte: ISODate("2016-04-29T00:00:00.000Z"),
        $lt: ISODate("2017-05-01T00:00:00.000Z")
    }
})
+1

Source: https://habr.com/ru/post/1667402/


All Articles