Kiran Muralee
Kiran Muralee

Reputation: 2060

Sorting inside a document in Yii2 mongodb

I am doing an application with Yii2 and mongodb.I want to retrieve records of a client based on id and sort the events of that client by date in descending order.But my code is not working.Please help me to find the issue.

The 'client' Collection's document is given below

{
    "_id" : ObjectId("55c397646ac8e41812000029"),
    "name" : "Krishnapriya",
    "location" : "Karunagapalli",
    "address" : "",
    "phoneno" : [ 
        "8765456789"
    ],
    "email" : [ 
        "[email protected]"
    ],
    "category" : "0",
    "notes_on_user" : "",
    "event" : [ 
        {
            "event_title" : "Sony Home Theater",
            "event_call_or_visit_purpose" : "2",
            "event_notes" : "She enquired about new Sony XXX 5.1 Channel Home theater",
            "event_call_or_visit" : "1",
            "event_datetime" : ISODate("2015-08-06T17:23:46.000Z")
        }, 
        {
            "event_title" : "San Disk Pendrive",
            "event_call_or_visit_purpose" : "1",
            "event_notes" : "She wants the pendrive to be repaired by 2 days",
            "event_call_or_visit" : "2",
            "event_datetime" : ISODate("2015-08-06T17:31:07.000Z"),
            "item" : {
                "item_name" : "San Disk 4gb",
                "item_model" : "San disk",
                "item_description" : " Pendrive not in reading condition",
                "item_accessories" : []
            }
        }
    ]
}

Here I want to get the document's 'event' array sorted with 'event_datetime' field in descending order .My controller code is given below.

       $clientdetail = Yii::$app->mongodb->getCollection('client');
       $result = $clientdetail->find(["_id" =>$id])->sort(["event.event_datetime"=> -1]);

       Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
       return $result;

Upvotes: 1

Views: 1670

Answers (1)

Mahesh Joshi
Mahesh Joshi

Reputation: 628

$query = Customer::find()->addOrderBy(['name'=> SORT_DESC, 'email' => SORT_DESC]);
$arrayDataProvider = new ArrayDataProvider([
        'allModels' => $query->all(),    
        'pagination' => ['pageSize' => 20],
    ]);

It works

Upvotes: 1

Related Questions