【问题标题】:Mongo distinct query with sort not working排序不工作的Mongo独特查询
【发布时间】:2020-10-21 19:21:36
【问题描述】:

我正在使用这样的 php 在 mongo 中运行查询:

$column ='address.roadname';



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

查询给出了结果,但没有排序。
我错过了什么?

数据只是“嵌套”到内部对象中的字符串
我期望的是按字母顺序排列的街道名称列表

样本数据:

[
  {
    "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"
      }
    ]
  }
]

我的期望:

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

注意:如果我在 mongo 控制台上运行它


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

我得到了预期的结果

【问题讨论】:

    标签: php mongodb sorting distinct-values


    【解决方案1】:

    distinct 的 PHP 实现确实有一个 sort 选项,请参阅 https://docs.mongodb.com/php-library/v1.7/reference/method/MongoDBCollection-distinct/

    在您的 shell 示例中,

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

    返回一个数组,因此当您在其上运行 .sort() 时,它使用的是 javascript Array.sort 方法。

    PHP distinct 函数也返回一个数组,所以在其上使用sort 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多