问题
i have a mongo php query with aggregate frame work, now i want to add sorting and select distinct criteria to that query, please not that my query is working perfectly without these two criterias,
take a look
$result = $collection->aggregate(array(
array(
'$match' => array(
'Details.Model' =>"AUDI",
'Details.Color' => "RED",
"Category" =>"Car"
)
),
array(
'$unwind' => '$Details'
),
array(
'$match' => array(
'Details.Model' =>"AUDI",
'Details.Color' => "RED",
"Category" =>"Car"
)
),
array(
'$project' => array(
'Pvalue' => '$Details.Price',
"Ovalue" =>'$Details.OwnerNameFirst',
"Cvalue"=>''$Category"
),
)
));
what i want is to sort Details.Price
in descending order, also Catagory
and Details.OwnerNameFirst
as Select Distinct
Please help
this is the result, value of $result
[{"_id":{"$id":"537dbca305a7d12f06000001"},"Pvalue":"60000","Ovalue":"jason","Cvalue":"Car"},{"_id": {"$id":"537dbca305a7d12f06000001"},"Pvalue":"59000","Ovalue":"george","Cvalue":"Jeep"},{"_id":{"$id":"537dbca305a7d12f06000001"},"Pvalue":"61000","Ovalue":"rahul""Cvalue":"Car"}]
回答1:
Seems mostly there, but the question is that if we are "grouping" ( which means distinct ) then that implies there are more than one value here for "price".
So which do you want? $min $max $first $last or $avg ?
I'll use $avg as the example, but replace according to your needs:
$result = $collection->aggregate(array(
array(
'$match' => array(
'Details.Model' =>"AUDI",
'Details.Color' => "RED",
"Category" =>"Car"
)
),
array(
'$unwind' => '$Details'
),
array(
'$match' => array(
'Details.Model' =>"AUDI",
'Details.Color' => "RED",
"Category" =>"Car"
)
),
array(
'$group' => array(
'_id' => array(
"Ovalue" =>'$Details.OwnerNameFirst',
"Cvalue"=>''$Category"
),
'Pvalue' => array(
'$avg' => '$Details.Price'
)
)
),
array(
'$sort' => array(
'Pvalue' => -1,
)
)
));
So once you have a value by the distinct keys then you just add a $sort stage. But pick which of the group operators you actually want.
回答2:
Check the docs for $sort:
$sort: {
Details.Price: -1
}
PHP equivalent:
array(
'$sort' => array("$Details.Price" => -1),
)
Check the PHP docs for more info.
来源:https://stackoverflow.com/questions/23865884/how-to-do-sorting-and-select-distinct-in-mogodb-php-query