How to do sorting and select distinct in mogodb php query

泄露秘密 提交于 2020-01-17 03:53:08

问题


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

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