我有这些文件
{
"_id": ObjectId("54de59a73674754822a1d71c"),
"date": ISODate("2015-02-13T00:00:00.0Z"),
"code1": "AAA",
"code2": "BBB",
"currency": "€",
"price": 177.6
}
{
"_id": ObjectId("54de59a73674754822a1d71c"),
"date": ISODate("2015-02-13T00:00:00.0Z"),
"code1": "AAA",
"code2": "BBB",
"currency": "€",
"price": 90.6
}
{
"_id": ObjectId("54de59a73674754822a1d71c"),
"date": ISODate("2015-02-13T00:00:00.0Z"),
"code1": "AAA",
"code2": "BBB",
"currency": "€",
"price": 150.6
}
{
"_id": ObjectId("54de59a73674754822a1d71c"),
"date": ISODate("2015-02-13T00:00:00.0Z"),
"code1": "CCC",
"code2": "DDD",
"currency": "€",
"price": 100.6
}
我希望使用mongodb的聚合框架按code1和code2对文档进行分组,以便: - 计算出现次数,然后 - 使用$ last运算符从组中获得最便宜的。
这是我的代码,它正在根据事件对文档进行排序,但是$ last给了我一个随机文档,而不是组中最便宜的文档。
public function aggregateQuery(){
$connection= new \MongoClient('server');
$dbname = $connection->selectDB('db');
$collection = $dbname->selectCollection('collection');
$parameters = array();
$match = array('currency' => "€");
array_push($parameters, array('$match' => $match));
$group_parameters = array('_id' => array('code1' => '$code1', 'code2' => '$code2'), 'price' => array('$last' =>'$price'), 'occurrences' => array('$sum' => 1));
array_push($parameters, $array('$group' => group_parameters));
array_push($parameters, array('$sort' => array('occurrences' => 1)));
return $$collection->aggregate($parameters);
}
我想得到的结果是: AAA - BBB:90.6 CCC - DDD:100.6
想法? 谢谢!