Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb query. How find the nearest to current date?

Tags:

mongodb

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

like image 330
victorpacheco3107 Avatar asked Jan 20 '17 23:01

victorpacheco3107


People also ask

How does MongoDB match current date?

$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 ( { } ).

How do I compare two dates in MongoDB?

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.

How does MongoDB store current date and time?

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.

What is ISODate in MongoDB?

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.


1 Answers

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.

like image 78
ares Avatar answered Sep 27 '22 20:09

ares