mongo- 投影时将一个字段的字段值转换为创建日期时间

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

我正在使用 mongodb 同意框架,这就是我的普通对象的样子

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

这里的history.dtEntry是一个纪元值(请不要建议我在进入这里之前将其更改为isodate,这超出了我的范围)。 我想将 c、p history.type 和 history.dtEntry 投影为(月中的某天)。

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

如果我直接使用任何纪元值,那么月份的日期就可以了,但是我必须传递 dtEntry 的值,而且这两种方法似乎都不适合我 我试过了

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

我发现了一些其他方法可能会对您有所帮助,请查看下面的聚合查询

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