MongoDB groupby distinct sort together

那年仲夏 提交于 2019-12-12 05:18:20

问题


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), 
 }

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))),

               ));

in output i want 2 fields "entity_id" and "year". can anyone suggest me best way of doing it. Thanks in advance.


回答1:


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' )
    ))
));

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.



来源:https://stackoverflow.com/questions/28803480/mongodb-groupby-distinct-sort-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!