我正在尝试使用日期聚合运算符调整时区。
我需要对 $signs.timestamp
字段进行 -7 小时调整。
这是我的代码:
function statsSignatures() {
$cursor = $this->db->collection->users->aggregate(
array('$unwind' => '$signs'),
array('$project'=>array(
'signs'=>'$signs',
'y'=>array('$year'=>'$signs.timestamp'),
'm'=>array('$month'=>'$signs.timestamp'),
'd'=>array('$dayOfMonth'=>'$signs.timestamp'),
'h'=>array('$hour'=>'$signs.timestamp')
)),
array('$group'=>array(
'_id'=>array('year'=>'$y','month'=>'$m','day'=>'$d','hour'=>'$h'),
'total'=>array('$sum'=>1)
)),
array('$sort'=>array(
'_id.year'=>1,
'_id.month'=>1,
'_id.day'=>1,
'_id.hour'=>1
))
);
return $cursor['result'];
}
我使用的是 MongoDB 2.6.3 版。
非常感谢!
最佳答案
您可以将 $project
与 $subtract 一起使用运算符对日期字段进行 -7 小时调整:
{
$project : {
ts : { $subtract : [ "$signs.timestamp", 25200000 ] }
}
}
// 25200000 == 1000 milis x 60 sec x 60 mins x 7 h
投影字段 ts
是一个偏移 -7 小时的日期。
编辑
这是使用 $subtract 时正确的 PHP 语法。
array(
'$project' => array(
'ts' => array('$subtract' => array('$signs.timestamp', 25200000))
)
)
Subtract 接受值数组,而不是键=>值对。
关于php - mongodb 日期聚合运算符时区调整与 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24738446/