简体   繁体   English

排序不工作的Mongo独特查询

[英]Mongo distinct query with sort not working

I'm running a query in mongo using php like this:我正在使用 php 在 mongo 中运行查询,如下所示:

$column ='address.roadname';



(new MongoDB\Client())->db->mycollection->distinct($column,[],['$sort'=> [$column => 1]]);

The query gives results, but those are not sorted.查询给出了结果,但没有排序。
What am I missing?我错过了什么?

The data are just strings "nested" into inner object数据只是“嵌套”到内部 object 中的字符串
What I expect is a list of street names sorted alphabetically我期望的是按字母顺序排序的街道名称列表

sample data:样本数据:

[
  {
    "name": "tizio",
    "address": [
      {
        "roadType": "via",
        "roadname": "Roma",
        "number": "12 bis",
        "city": "Milano"
      },
      {
        "roadType": "via",
        "roadname": "Emilia",
        "number": "124",
        "city": "Modena"
      },
      {
        "roadType": "via",
        "roadname": "Appia",
        "number": "89",
        "city": "Genova"
      }
    ]
  },
  {
    "name": "caio",
    "address": [
      {
        "roadType": "vicolo",
        "roadname": "stretto",
        "number": "12",
        "town": "Monza"
      },
      {
        "roadType": "largo",
        "roadname": "Garibaldi",
        "number": "24",
        "city": "Modena"
      },
      {
        "roadType": "piazza",
        "roadname": "Armi",
        "number": "26",
        "city": "Rovigo"
      }
    ]
  },
  {
    "name": "sempronio",
    "address": [
      {
        "roadname": "Roma",
        "number": "15",
        "city": "Milano"
      },
      {
        "roadType": "via",
        "roadname": "Po",
        "number": "4",
        "city": "Torino"
      },
      {
        "roadType": "largo",
        "roadname": "Garibaldi",
        "number": "9",
        "community": "Genova"
      }
    ]
  }
]

what I expect:我的期望:

Appia,Armi,Emilia,Garibaldi,Po,Roma,Stretto

note: if I run it on mongo console注意:如果我在 mongo 控制台上运行它


db.mycollection.distinct("address.roadname").sort() 

I got the expected result我得到了预期的结果

The PHP implementation of distinct does have a sort option, see https://docs.mongodb.com/php-library/v1.7/reference/method/MongoDBCollection-distinct/ distinct 的 PHP 实现确实有一个sort选项,请参阅https://docs.mongodb.com/php-library/v1.7/Colctionreference/method/MongoDBle-dis

In your shell example,在您的 shell 示例中,

db.mycollection.distinct("address.roadname")

returns an array, so when you run .sort() on that it is using the javascript Array.sort method.返回一个数组,因此当您对其运行.sort()时,它正在使用 javascript Array.sort方法。

The PHP distinct function also returns an array, so use the sort function on it. PHP 不同的 function 也返回一个数组,所以使用排序function 就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM