Brij Raj Singh - MSFT
Brij Raj Singh - MSFT

Reputation: 5113

mongo- convert the field value of one field to create datetime during projection

I am using the mongodb agreegate framework, and this is how my normal object looks like

{
    "_id" : "6b109972c9bd9d16a09b70b96686f691bfe2f9b6",
     "history" : [ 
        {
            "dtEntry" : 1428929906,
            "type" : "I",
            "refname" : "ref1"
        }, 
        {
            "dtEntry" : 1429082064,
            "type" : "U",
            "refname" : "ref1"
        }
    ],
    "c" : "SomeVal",
    "p" : "anotherVal"
}

here the history.dtEntry is an epoch value (please don't advise me to change this to isodate before entering here, Its out of my scope). I want to project the c,p history.type,and history.dtEntry as (day of month).

db.mydataset.aggregate({$project:{c:1,p:1,type:"$history.type",DtEntry:"$history.dtEntry",dater:{$dayOfMonth:new Date(DtEntry)}}})

if I use any epoch value directly the day of month comes out just fine, but I have to pass the value of dtEntry and neither of the ways seem to work for me I have tried

$dayOfMonth:new Date(DtEntry)
$dayOfMonth:new Date(history.DtEntry)
$dayOfMonth:new Date("history.DtEntry")
$dayOfMonth:new Date("$history.DtEntry")

Upvotes: 2

Views: 354

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

I found some other ways may be this will help you, check below aggregation query

db.collectionName.aggregate({
"$unwind": "$history"
}, {
"$project": {
    "c": 1,
    "p": 1,
    "type": "$history.type",
    "dater": {
        "$dayOfMonth": {
            "$add": [new Date(0), {
                "$multiply": ["$history.dtEntry", 1000]
            }]
        }
    }
}
})

Upvotes: 2

Related Questions