【问题标题】:Mongodb and sorting sub arrayMongodb和排序子数组
【发布时间】:2012-07-28 16:35:54
【问题描述】:

不确定这是否可以做到,所以我想我会问。

我有以下 mongodb/s

{
 "store":"abc",
 "offers":[{
    "spend":"100.00",
    "cashback":"10.00",
    "percentage":"0.10"
  },{
    "spend":"50.00",
    "cashback":"5.00",
    "percentage":"0.10"
  }]
}

 {
     "store":def",
     "offers":[{
        "spend":"50.00",
        "cashback":"2.50",
        "percentage":"0.05"
      },{
        "spend":"20.00",
        "cashback":"1.00",
        "percentage":"0.05"
      }]
    }

 {
         "store":ghi",
         "offers":[{
            "spend":"50.00",
            "cashback":"5.00",
            "percentage":"0.10"
          },{
            "spend":"20.00",
            "cashback":"2.00",
            "percentage":"0.10"
          }]
        }

需要按百分比排序。

我不确定是否必须使用另一个 PHP 函数的 usort 来执行此操作,或者 Mongodb 是否足够聪明以执行我想做的事情。

【问题讨论】:

    标签: php mongodb sorting


    【解决方案1】:

    很神奇,是的,mongodb 可以做到这一点:

    // Sort ascending, by minimum percentage value in the docs' offers array.
    db.collection.find({}).sort({ 'offers.percentage': 1 });
    
    // Sort descending, by maximum percentage value in the docs' offers array.
    db.collection.find({}).sort({ 'offers.percentage': -1 });
    

    【讨论】:

    • 这可能会对文档进行排序,但不确定这对文档中的数组有什么帮助……或者 Mongo 如何处理未排序的数组。例如,要对 %s 为 0.05、0.10 的文档与另一个 0.10、0.05 的文档进行可预测的排序。
    • 如果每个报价都在自己的集合行中会更好
    【解决方案2】:

    鉴于文档中数组的数据结构,我认为在 MongoDB 中进行这种排序没有意义——Mongo 将返回整个文档(而不是数组)。

    如果您尝试比较报价,则使用单独的集合而不是嵌入式数组可能更有意义。例如,您可以找到匹配至少 5 美元现金返还的优惠,按支出或折扣百分比排序。

    如果您只是想在单个文档中订购商品,您可以在 PHP 中使用 usort() 进行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多