How to convert milliseconds to date in mongodb aggregation?

前端 未结 1 1953
悲&欢浪女
悲&欢浪女 2021-01-14 06:35

I have a collection in MongoDB and documents like this -

[
    {
        \"campaignId\": 1,
        \"operatorId\": 1,
        \"txnType\": \"DR\",
                 


        
1条回答
  •  -上瘾入骨i
    2021-01-14 07:17

    You could try adding the milliseconds time to a zero-milliseconds Date() object in the $project operator using the $add arithmetic operator, so an aggregation pipeline like the following will give you the timestamp field converted to Date:

    db.campaign_wallet.aggregate([
        { 
            "$match": { 
                "campaignId" : 1 , 
                "txnTime" : { 
                    "$gte" : 1429554600000 , 
                    "$lte" : 1430159400000
                }
            }
        },
        { 
            "$group" : { 
                "_id" : {
                    "txnTime" : "$txnTime",
                    "msisdn":"$msisdn"
                }, 
                "msisdnCount" : { "$sum" : 1}
            }
        },
        { 
            "$group" : { 
                "_id" : "$_id.txnTime", 
                "msisdns" : { 
                    "$push" :{
                        "txnTime" : "$_id.txnTime", 
                        "count" : "$msisdnCount"
                    },
                }, 
                "count" : { 
                    "$sum" : "$msisdnCount"
                }
            }
        },
        {
            "$unwind": "$msisdns"
        },
        {
            "$project": {
                "msisdns": {
                    "txnTime" : {
                        "$add": [ new Date(0), "$msisdns.txnTime" ]
                    }
                },
                "msisdns.count": 1,
                "count": 1
             } 
        }
    ]);
    

    Output:

    /* 0 */
    {
        "result" : [ 
            {
                "_id" : 1430111514796,
                "msisdns" : {
                    "txnTime" : ISODate("2015-04-27T05:11:54.796Z"),
                    "count" : 1
                },
                "count" : 1
            }, 
            {
                "_id" : 1430111514900,
                "msisdns" : {
                    "txnTime" : ISODate("2015-04-27T05:11:54.900Z"),
                    "count" : 1
                },
                "count" : 1
            }
        ],
        "ok" : 1
    }
    

    0 讨论(0)
提交回复
热议问题