1

Is that possible to sort data in sub array in mongo database?

{   "_id" : ObjectId("4e3f8c7de7c7914b87d2e0eb"), 
    "list" : [
            {
                "id" : ObjectId("4e3f8d0be62883f70c00031c"),
                "datetime" : 1312787723,
                "comments" : 
                    {
                        "id" : ObjectId("4e3f8d0be62883f70c00031d")
                        "datetime": 1312787723,
                    },
                    {
                        "id" : ObjectId("4e3f8d0be62883f70c00031d")
                        "datetime": 1312787724,
                    },                  
                    {
                        "id" : ObjectId("4e3f8d0be62883f70c00031d")
                        "datetime": 1312787725,
                    },
            }
        ], 
    "user_id" : "3" }

For example I want to sort comments by field "datetime". Thanks. Or only variant is to select all data and sort it in PHP code, but my query works with limit from mongo...

1 Answer 1

2

With MongoDB, you can sort the documents or select only some parts of the documents, but you can't modify the documents returned by a search query.

If the current order of your comments can be changed, then the best solution would be to sort them in the MongoDB documents (find(), then for each doc, sort its comments and update()). If you want to keep the current internal order of comments, then you'll have to sort each document after each query.

In both case, the sort will be done with PHP. Something like:

foreach ($doc['list'] as $list) {
    // uses a lambda function, PHP 5.3 required
    usort($list['comments'], function($a,$b){ return $a["datetime"] < $b["datetime"] ? -1 : 1; });
}

If you can't use PHP 5.3, replace the lambda function by a normal one. See usort() examples.

Sign up to request clarification or add additional context in comments.

2 Comments

thx, I have done like that, but I think can do it with mongo, but Thx for reply;)
If you have a solution, it would be nice to share it with the rest of us.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.