我在Mongo Aggregate查询中使用$ match两次出现问题。当查询输入到数组中时,它似乎会覆盖第一个$ match与第二个$ match匹配,因此无法正确查询。有没有办法用两个匹配查询?
$aggArray = array(array(
'$match'=>array('payload.location.coordinates.0'=>array('$gte'=>$longmin,'$lte'=>$longmax),'payload.location.coordinates.1'=>array('$gte'=>$latmin,'$lte'=>$latmax),'time'=>array('$gte'=>new MongoDate($time1),'$lte'=>new MongoDate($time2))),
'$project'=>array('payload.location.coordinates'=>1,'time'=>array('$hour'=>'$time')),
'$match'=>array('time'=>array('$gte'=>10,'$lte'=>12))
));
我目前在Mongo的查询是:
db.getCollection('datas').aggregate(
{"$match":{"payload.location.coordinates.0":{"$gte":-0.489,"$lte":0.236},"payload.location.coordinates.1":{"$gte":51.28,"$lte":51.686},"time":{"$gte":new Date(2016,0,10),"$lte":new Date(2016,0,12)}}},
{"$project":{"payload.location.coordinates":1,"time":{"$hour":"$time"}}},
{"$match":{"time":{"$gte":10,"$lte":12}}})
这会在一段时间内(在这种情况下,1月10日到1月12日)在某个地理边界框({{1}})内获取一组数据,查询。然后它会在每个记录的小时内进行预测,然后查询这些日期(payload.location.coordinates
)内给定小时范围内的记录。输出是原始数据系列的一组结果,在两个日期之间的上午10点到12点之间返回time:{"$gte":10,"$lte":12}
(小时)和time
。
答案 0 :(得分:2)
首先创建一个 $project
步骤,用于投影其他字段以及显示日期时间字段time
的小时部分的新字段。然后,下一阶段应将两个过滤器(即坐标,日期和小时范围)合并为一个 $match
管道步骤。
Mongo查询
var start = new Date(time1);
var end = new Date(time2);
var aggArray = [
{
"$project": {
"coordinates": "$payload.location.coordinates",
"datetime": "$time",
"hour_part": { "$hour": "$time" }
},
},
{
"$match": {
"coordinates.0": { "$gte": longmin, "$lte": longmax},
"coordinates.1": { "$gte": latmin, "$lte": latmax},
"datetime": { "$gte": start, "$lte": end },
"hour_part": { "$gte": 10, "$lte": 12 }
}
}
];
PHP等效
$start = new MongoDate($time1);
$end = new MongoDate($time2);
$aggArray = array(
array(
"$project" => array(
"coordinates" => "payload.location.coordinates",
"datetime" => "$time",
"hour_part": array( "$hour" => "$time" )
),
),
array(
"$match" => array(
"coordinates.0" => array(
"$gte" => $longmin,
"$lte" => $longmax
),
"coordinates.1" => array(
"$gte" => $latmin,
"$lte" => $latmax
),
"datetime" => array(
"$gte" => $start,
"$lte" => $end
),
"hour_part" => array(
"$gte" => 10,
"$lte" => 12
)
)
)
);