3

I am wondering if there is a way to get a MongoDB document age in hours? Here's what I have so far, but obviously I'm using a date object, it is not calculating the hours, and it's not giving the age, just the date it was created, so it is not giving the desired result. In fact, the $divide pipeline does not even allow for date objects. Any help is appreciated. Just as an FYI, the $views variable is a NumberInt32 type and the $created_at variable is a timestamp, like: 2014-05-20T00:01:08.629Z.

db.projects.aggregate({ 
    $project: { 
        "result": {
            $divide: ['$views', '$created_at']
        }
    }
)

If you're wondering, this code is to help sort popular posts, but of course, it's only part of it. Thanks for any help!

1
  • Why can't you just use the created at date as part of the query? Match all docs created now minus two hours ago for example. Commented May 20, 2014 at 11:04

1 Answer 1

2

Presuming that $views and $created_at are fields in your document containing a number of views and the created timestamp as follows:

{
    "_id" : ObjectId("537abe5e8da9877dbb0ef604"),
    "views" : 5,
    "created_at" : ISODate("2014-05-20T00:00:00Z")
}

Then just a little date math getting the difference from the current time should do:

db.projects.aggregate([
    { "$project": { 
        "score": { "$divide": [
            { "$divide": [
                { "$subtract": [ 
                    new Date(), 
                    "$created_at" 
                ]},
                100*60*60
            ]},
            "$views"
        ]},
        "created_at": 1,
        "views": 1
    }}
])

So you are basically getting the difference in hours from the current time as a date object and the created_at value. Dividing that by a standard number for hours in a day, then dividing by your views in order to get your "score" result for sorting.

When you do math operations with two date objects then the result is returned as a number. So further operations with just numbers will work from then on.

Sign up to request clarification or add additional context in comments.

2 Comments

You're awesome, man! I'll test this code tomorrow and get back to you.
Works great, man! There was an issue with the score getting smaller as the views value increased, but that was fixed by changing it so the $views value would be divided by the age, instead of the other way around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.