我在尝试从收集中获取HOUR并减去3小时(GMT-3)时遇到了麻烦
如果我跑
db.post.aggregate(
[{$match : {'uri' : /fantastic/ } },
{
$project:
{
_id: 0,
created_at : 1,
date_minus_3 : {$subtract:["$created_at",3*60*60*1000]},
hour_from_original: { $hour: "$created_at" }
}
}
]
)
我得到了
(...)
{
"created_at" : ISODate("2014-06-03T02:51:42.000Z"),
"date_minus_3" : ISODate("2014-06-02T23:51:42.000Z"),
"hour_from_original" : 2
},
(...)
但如果我从“date_minus_3”
获取小时 db.post.aggregate(
[{$match : {'uri' : /fantastic/ } },
{
$project:
{
_id: 0,
created_at : 1,
date_minus_3 : {$subtract:["$created_at",3*60*60*1000]},
hour_from_original: { $hour: "$created_at" },
hour_from_date_minus_3 : {$hour: {$subtract:["$created_at",3*60*60*1000]}}
}
}
]
)
我收到错误消息
Error("Printing Stack Trace")@:0
()@src/mongo/shell/utils.js:37
([object Array])@src/mongo/shell/collection.js:866
@(shell):10
uncaught exception: aggregate failed: {
"errmsg" : "exception: the $hour operator does not accept an object as an operand",
"code" : 16021,
"ok" : 0
}
任何人都可以帮助我吗?
答案 0 :(得分:0)
只需拥有两个单独的 $project
管道,您可以使用第一个 $project
管道阶段计算日期减去三小时的字段,然后然后,下一个管道步骤将$hour
运算符应用于新的减去3小时的日期。
假设您为测试目的插入了以下测试文档:
db.test.insert([
{"created_at" : ISODate("2014-06-03T02:51:42.000Z")},
{"created_at" : ISODate("2014-06-04T11:23:17.000Z")}
])
上面的汇总管道可以提供日期减去3的小时部分:
db.test.aggregate([
{
$project:
{
_id: 0,
created_at : 1,
date_minus_3 : {$subtract:["$created_at",3*60*60*1000]},
hour_from_original: { $hour: "$created_at" }
}
},
{
$project:
{
_id: 0,
created_at : 1,
date_minus_3 : 1,
hour_from_original: 1,
hour_from_date_minus_3 : { $hour: "$date_minus_3" }
}
}
]);
<强>结果强>:
/* 0 */
{
"result" : [
{
"created_at" : ISODate("2014-06-03T02:51:42.000Z"),
"date_minus_3" : ISODate("2014-06-02T23:51:42.000Z"),
"hour_from_original" : 2,
"hour_from_date_minus_3" : 23
},
{
"created_at" : ISODate("2014-06-04T11:23:17.000Z"),
"date_minus_3" : ISODate("2014-06-04T08:23:17.000Z"),
"hour_from_original" : 11,
"hour_from_date_minus_3" : 8
}
],
"ok" : 1
}