Ravi Solanki
Ravi Solanki

Reputation: 63

How to get sum of differences from two dates in mongodb

I want to sum of differences from starttime and endtime in minutes.

{
    "_id" : ObjectId("56cd544df7851e850d8b4573"),
    "user_id" : "281",
    "document_id" : "1455614372.pdf",
    "page_number" : "1",
    "starttime" : ISODate("48118-03-20T01:35:14Z"),
    "endtime" : ISODate("48118-03-20T04:29:10Z")
}
{
    "_id" : ObjectId("56cd544df7851e850d8b4574"),
    "user_id" : "281",
    "document_id" : "1455614372.pdf",
    "page_number" : "1",
    "starttime" : ISODate("48118-03-20T14:29:49Z"),
    "endtime" : ISODate("48118-06-22T12:52:36Z")
}
{
    "_id" : ObjectId("56cd544df7851e850d8b4575"),
    "user_id" : "281",
    "document_id" : "1455614372.pdf",
    "page_number" : "2",
    "starttime" : ISODate("48118-03-20T04:29:10Z"),
    "endtime" : ISODate("48118-03-20T14:29:49Z")
}

my collection name is pdftracker.

Upvotes: 5

Views: 2133

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

You don't say which fields you want to group on, but assuming you want a "user_id" and "document_id" combination. Whatever it's just the _id field in the following $group statement.

As for the "interval", then date math is on your side, and when you $subtract one Date object from another, then the result is the "difference" represented in "milliseconds". So that again just takes a little conversion:

db.collection.aggregate([
    { "$group": {
        "_id": { "user_id": "$user_id", "document_id": "$document_id" },
        "totalMinites": {
            "$sum": {
                "$divide": [
                    { "$subtract": [ "$endtime", "$starttime" ] },
                    1000 * 60
                ]
            }
        }
    }}
])

Simple math rolled into $sum for the total on the grouping. And 1000 milliseconds multiplied by 60 seconds as a divisor on a millisecond result does the conversion to minutes.

Upvotes: 5

Related Questions