我有这样的mongodb 1集合结构-
{
"_id" : ObjectId("54d34cb314aa06781400081b"),
"entity_id" : NumberInt(440),
"year" : NumberInt(2011),
}
{
"_id" : ObjectId("54d34cb314aa06781400081e"),
"entity_id" : NumberInt(488),
"year" : NumberInt(2007),
}
{
"_id" : ObjectId("54d34cb314aa06781400081f"),
"entity_id" : NumberInt(488),
"year" : NumberInt(2008),
}
{
"_id" : ObjectId("54d34cb314aa067814000820"),
"entity_id" : NumberInt(488),
"year" : NumberInt(2009),
}
{
"_id" : ObjectId("54d34cb314aa067814000827"),
"entity_id" : NumberInt(489),
"year" : NumberInt(2009),
}
所以在输出中,我希望我只得到最大值为"year"的"entity_id"。(假设"488"entity_id的"年份"应为2009年)。我试过写查询
$fin_cursor = $db->command(array(
"distinct" =>"Profit_and_Loss",
"key" =>'entity_id',
"query" => array(array('$and'=>$financial_pl_search_array),array('$sort'=>array("year"=>-1))),
));
在输出中,我想要两个字段"entity_id"one_answers"year"。有人能给我推荐最好的方法吗。提前谢谢。
您最好使用.aggregate()
来完成此操作。这也是现代版本驱动程序中收集对象的直接方法:
$result = $db->collection('Profit_and_loss')->aggregate(array(
array( '$group' => array(
'_id' => '$entity_id',
'year' => array( '$max' => '$year' )
))
));
.distinct()
命令仅在单个字段上运行。正如您所指出的,其他表单需要JavaScript评估,并且运行速度比本机代码慢得多。