如何在mogodb php查询中进行排序和选择不同 [英] How to do sorting and select distinct in mogodb php query
问题描述
我有一个具有聚合框架工作的mongo php查询,现在我想对该查询添加排序并选择不同的条件,请不要在没有这两个条件的情况下我的查询就可以完美地工作,
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,
看看
$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"
),
)
));
我想要的是在 Catagory
和 Details.OwnerNameFirst
选择不同
what i want is to sort Details.Price
in descending order, also Catagory
and Details.OwnerNameFirst
as Select Distinct
请帮助
这是结果,$ result的值
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"}]
推荐答案
似乎大多数都在那儿,但是问题是,如果我们正在分组(这意味着与众不同),那么这意味着价格有多个值。
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".
那么您想要哪个? $ min
$ max
$ first
$ last
或< a href = http://docs.mongodb.org/manual/reference/operator/aggregation/avg/#grp._S_avg rel = nofollow> $ avg
?
So which do you want? $min
$max
$first
$last
or $avg
?
我将使用 $ 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,
)
)
));
因此,一旦您通过各个键获得一个值,则您可以必须添加 $ sort
阶段。但请选择您真正想要的组运算符。
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.
这篇关于如何在mogodb php查询中进行排序和选择不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!