MongoDB groupby distinct sort together

2019-09-03 11:25发布

问题:

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.