简体   繁体   English

如何使用PHP对嵌套的MongoDB集合进行排序

[英]How to sort nested MongoDB collection using PHP

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

I want to sort the above document, which is stored in MongoDB, and I am using PHP. 我想对存储在MongoDB中的上述文档进行排序,并且我正在使用PHP。

Scenario : In the frontend, I have a drop-down where I am showing trips (ie Tokyo, Paris, Goa) and I have a button with the title of "Price" to show the lowest to highest price trip. 场景 :在前端,我有一个下拉菜单,用于显示旅行(即东京,巴黎,果阿),并且有一个标题为“价格”的按钮,用于显示从最低到最高的价格旅行。

Question : 问题

  1. When I select, let's say, Paris and I click on the Price button, above document should be sorted by price (lowest to highest). 假设我选择巴黎,然后单击“价格”按钮,则上面的文档应按价格排序(从最低到最高)。

  2. Sort should be applied to the object where the destination is Paris. 排序应应用于目的地为巴黎的对象。

  3. This document can go up to 25/28 MB (Here I am just showing a small preview of my document). 该文档的最大大小为25/28 MB(此处我只是显示文档的小预览)。

What I tried : 我试过了

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

and many more. 还有很多。

Any small help much appreciated, Thank you. 任何小的帮助,不胜感激,谢谢。

Try this: 尝试这个:

$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);

This works for me. 这对我有用。

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

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