mongodb的示例文档:
{
"_id" : ObjectId("512eef329d5d0c9415000025"),
"time" : NumberLong(1431973102)
}
我想从aggreate查询中的time属性中保存的时间戳值获取$ dayOfMonth,但是我发现了这个例外消息:
uncaught exception: aggreate failed: {
"errmsg" : "exception: can't convert from BSON type NumberLong64 to Date",
"code" : 16006,
"ok" : 0
}
当我运行此查询时:
db.getCollection('collection_name').aggregate([
{ $match: { '_id': ObjectId('512eef329d5d0c9415000025') } },
{ $project: { 'time': 1, "dayOfMonth": { $dayOfMonth: '$time' } } }
])
有什么想法吗?谢谢。
答案 0 :(得分:1)
您首先需要使用$add
db.data.aggregate({
$project: {
"dayOfMonth": {
$dayOfMonth: {
$add: [new Date("1970-01-01"), {
$multiply: ["$time", 1000]
}]
}
}
}
})
对您的查询实施此操作会给出:
db.data.aggregate([
{$match: { '_id': ObjectId('512eef329d5d0c9415000025') } },
{$project: {"time": 1,"dayOfMonth": {$dayOfMonth: {$add: [new Date("1970-01-01"), {$multiply: ["$time", 1000]}]}}}}])
答案 1 :(得分:0)
如果您使用的是Java,我建议您使用Joda-Time库来转换纪元中的日期并提取所需的月份。
DateTime date = new DateTime(dateInMilli);
date.dayOfMonth();
如果日期未在应用程序的任何位置使用,那么您也可以将其保存为ISODate格式而不是Epoch。
如果您使用JS,那么JohnnyHK提供的链接会有更多信息。