We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Sorting a mongodb result by subdocument field

Hi,

I have a problem with sorting a mongodb query result by comments.created_at => -1 in a subdocument:

"comments" : [
        {
            "comment" : "My first comment",
            "created_at" : NumberLong(1488896632),
            "author" : {
                "email" : "[email protected]",
                "username" : "homeboy",
                "_id" : ObjectId("58bbd0561eab0026290dd8ed")
            }
        },
        {
            "comment" : "My second comment",
            "created_at" : NumberLong(1488896638),
            "author" : {
                "email" : "[email protected]",
                "username" : "homeboy",
                "_id" : ObjectId("58bbd0561eab0026290dd8ed")
            }
        },
        {
            "comment" : "My third comment",
            "created_at" : NumberLong(1488896644),
            "author" : {
                "email" : "[email protected]",
                "username" : "homeboy",
                "_id" : ObjectId("58bbd0561eab0026290dd8ed")
            }
        }
    ],

Following way did not work:

    Post::find(array(
        "conditions" => array(),
        "sort" => array("comments.created_at" => -1)
    ));

Have you any ideas? Thx!



47.6k
 Post::find(array( "conditions" => array(), "sort" => array("comments.created_at" => -1) ));

should be ?

 Post::find( array("sort" => array("created_at" => -1)  ) );