简体   繁体   中英

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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