MongoDB groupby不同的排序在一起 [英] MongoDB groupby distinct sort together
问题描述
我有像这样的mongodb 1集合结构-
i have mongodb 1 collections structure like this-
{
"_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"year"应为2009). 我尝试写查询
so in output i want that i should get "entity_id" with max "year" only .(suppose with "488" entity_id "year" should be 2009). i have tried writing query
$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))),
));
在输出中,我想要2个字段"entity_id"和"year". 谁能建议我最好的方法. 预先感谢.
in output i want 2 fields "entity_id" and "year". can anyone suggest me best way of doing it. Thanks in advance.
推荐答案
You're better of using .aggregate()
to do this. It's also a direct method on the collection objects in modern versions of the driver:
$result = $db->collection('Profit_and_loss')->aggregate(array(
array( '$group' => array(
'_id' => '$entity_id',
'year' => array( '$max' => '$year' )
))
));
.distinct()
命令仅在单个字段上运行.正如您所注意到的,其他形式都需要JavaScript评估,并且运行速度比本地代码慢得多.
The .distinct()
command only runs over a single field. Other forms require JavaScript evaluation as you have noted and run considerably slower than native code.
这篇关于MongoDB groupby不同的排序在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!