【问题标题】:How to sort nested MongoDB collection using PHP如何使用 PHP 对嵌套的 MongoDB 集合进行排序
【发布时间】:2016-08-30 13:29:33
【问题描述】:
[
    {
        "trip": [
            {
              "destination": "Tokyo",
              "time": 8.56,
              "price": 80
            },
            {
              "destination": "Paris",
              "time": 2.36,
              "price": 9
            },
            {
              "destination": "Goa",
              "time": 4.56,
              "price": 30
            }
        ]
    },
    {
        "trip": [
            {
              "destination": "Tokyo",
              "time": 6.26,
              "price": 23
            },
            {
              "destination": "Paris",
              "time": 7.46,
              "price": 45
            },
            {
              "destination": "Goa",
              "time": 8.98,
              "price": 39
            }
        ]
    }
]

我想对上面的文档进行排序,存储在MongoDB中,我使用的是PHP。

场景:在前端,我有一个显示旅行(即东京、巴黎、果阿)的下拉菜单,我有一个标题为“价格”的按钮来显示最低价到最高价的行程。

问题

  1. 当我选择巴黎时,假设我点击价格按钮,以上文档应按价格排序(从最低到最高)。

  2. 应该对目的地为巴黎的对象应用排序。

  3. 此文档最大为 25/28 MB(这里我只是显示我的文档的一个小预览)。

我尝试了什么

db.testCollection.find({
    'trip': { 
        $elemMatch: { 
            'destination':'Paris'
            } 
        }
    }).sort({
        "trip.price":1
    })

还有更多。

非常感谢任何小的帮助,谢谢。

【问题讨论】:

标签: mongodb php sorting


【解决方案1】:

试试这个:

$collection = $db->createCollection("emp_details");

$sort = array('col_name' => 1);   // you can change this array on the behalf of some condition like:

if(something)
{
    $sort = array('col_name' => 1);   // asc
}
else
{
    $sort = array('col_name' => -1);   // desc
}

$resultSet  = $collection->find()->sort($sort);

这对我有用。

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多