Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert milliseconds to date in mongodb aggregation pipeline for group by?

I have to convert milliseconds to date format in mongodb aggregation pipiline -

My query is -

db.campaign_wallet.aggregate({"$match" : {"campaignId" : 1, "txnTime" : { "$gte" : 1429554600000, "$lte" : 1430159400000}}}, {"$group" : {"_id" : {"msisdn" : "$msisdn", "txnTime" : "$txnTime"}, "count" : {"$sum": 1}}});

In this query how to convert txnTime (which is in milliseconds) to date in pipeline ?

like image 802
Amit Das Avatar asked Apr 27 '15 09:04

Amit Das


People also ask

How do I change the date format in aggregation in MongoDB?

If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the $dateToString aggregate pipeline operator. The $dateToString operator converts the Date object to a string, and optionally allows you to specify a format for the resulting output.

Which aggregate method is preferred for use by MongoDB?

The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. The aggregation pipeline can operate on a sharded collection. The aggregation pipeline can use indexes to improve its performance during some of its stages.

Can we use $and in aggregate MongoDB?

You can use $and with aggregation but you don't have to write it, and is implicit using different filters, in fact you can pipe those filters in case one of them needs a different solution.


2 Answers

I'm trying to get the logic behind converting the txnTime field to a date object because grouping by either a date field or a timestamp in milliseconds (like what you are presently doing) will yield the same result as they both are unique in their respective formats!

To change the txnTime field to a date object you should then include a $project pipeline before the $group pipeline stage with this expression

"txnTime": {
    "$add": [ new Date(0), "$txnTime" ]
}

so that you can do your $group operation on the converted/projected txnTime field:

var convertedTxnTime = { "$add": [new Date(0), "$txnTime"] };

/*
  If using MongoDB 4.0 and newer, use $toDate 

  var convertedTxnTime = { "$toDate": "$txnTime" };

  or $convert

  var convertedTxnTime = { "$convert": { "input": "$txnTime", "to": "date" } };

*/

db.campaign_wallet.aggregate([
    { "$match": { 
        "campaignId" : 1 , 
        "txnTime" : { 
            "$gte" : 1429554600000 , 
            "$lte" : 1430159400000
        }
    } },
    { "$group" : { 
        "_id" : {
            "txnTime": convertedTxnTime,
            "msisdn" : "$msisdn"
        }, 
        "msisdnCount" : { "$sum" : 1}
    } }
]);

Output: (based on the sample documents from this question)

/* 0 */
{
    "result" : [ 
        {
            "_id" : {
                "txnTime" : ISODate("2015-04-25T18:30:00.000Z"),
                "msisdn" : "91808770101"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime" : ISODate("2015-04-27T05:11:54.796Z"),
                "msisdn" : "9180877010"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime" : ISODate("2015-04-25T18:30:01.111Z"),
                "msisdn" : "91808070101"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime" : ISODate("2015-04-25T18:30:00.000Z"),
                "msisdn" : "91808070101"
            },
            "msisdnCount" : 2
        }, 
        {
            "_id" : {
                "txnTime" : ISODate("2015-04-27T05:11:54.796Z"),
                "msisdn" : "9189877000"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime" : ISODate("2015-04-27T05:11:54.796Z"),
                "msisdn" : "9189877667"
            },
            "msisdnCount" : 1
        }
    ],
    "ok" : 1
}

-- UPDATE --

To group the documents by date with the format YYYY-MM-DD, use the Date Aggregation Operators

Example:

var convertedTxnTime = { "$add": [new Date(0), "$txnTime"] };

/*
  If using MongoDB 4.0 and newer, use $toDate 

  var convertedTxnTime = { "$toDate": "$txnTime" };

  or $convert

  var convertedTxnTime = { "$convert": { "input": "$txnTime", "to": "date" } };

*/

db.campaign_wallet.aggregate([
    { "$match": { 
        "campaignId" : 1 , 
        "txnTime" : { 
            "$gte" : 1429554600000 , 
            "$lte" : 1430159400000
        }
    } },
    { "$group" : { 
        "_id" : {
            "txnTime_year" : { "$year": convertedTxnTime },
            "txnTime_month" : { "$month": convertedTxnTime },
            "txnTime_day" : { "$dayOfMonth": convertedTxnTime },
            "msisdn": "$msisdn"
        }, 
        "msisdnCount" : { "$sum" : 1}
    } }
]);

Output:

/* 0 */
{
    "result" : [ 
        {
            "_id" : {
                "txnTime_year" : 2015,
                "txnTime_month" : 4,
                "txnTime_day" : 25,
                "msisdn" : "91808770101"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime_year" : 2015,
                "txnTime_month" : 4,
                "txnTime_day" : 25,
                "msisdn" : "91808070101"
            },
            "msisdnCount" : 3
        }, 
        {
            "_id" : {
                "txnTime_year" : 2015,
                "txnTime_month" : 4,
                "txnTime_day" : 27,
                "msisdn" : "9180877010"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime_year" : 2015,
                "txnTime_month" : 4,
                "txnTime_day" : 27,
                "msisdn" : "9189877000"
            },
            "msisdnCount" : 1
        }, 
        {
            "_id" : {
                "txnTime_year" : 2015,
                "txnTime_month" : 4,
                "txnTime_day" : 27,
                "msisdn" : "9189877667"
            },
            "msisdnCount" : 1
        }
    ],
    "ok" : 1
}
like image 102
chridam Avatar answered Sep 18 '22 08:09

chridam


With mongodb 4.0 you can try $toDate aggregation to convert milliseconds to date format

db.collection.aggregate([
  { "$match": { 
    "campaignId" : 1 , 
    "txnTime" : { 
      "$gte" : 1429554600000 , 
      "$lte" : 1430159400000
    }
  }},
  { "$project": {
    "toDate": {
      "$toDate": "$txnTime"
    }
  }}
])

You can try it here

like image 23
Ashh Avatar answered Sep 17 '22 08:09

Ashh