0

Hello everybody I have a document is structured like that:

{
    name : abc
    message:
    [{
         id: 4,
         status : 0,
         content : "abc"
     },
     {
         id: 2,
         status : 1,
         content : "abc"
     },
     {
         id: 1,
         status : 1,
         content : "abc"
     }
    ]
}

How Can I get the sorted message array by id key and status = 1 I mean

{
     id: 1,
     status : 1,
     content : "abc"
 },
 {
     id: 2,
     status : 1,
     content : "abc"
 },

Thank so much!

0

1 Answer 1

1

This solutin in mongo shell, should work out for you. But the aggregate framework is supported from Mongo 2.1 onwards. http://docs.mongodb.org/manual/applications/aggregation/

    db.yourcollection.aggregate([{$unwind:"$message"},{$match:{"message.status":1}},{$project:{_id:0,message:1}},{$sort:{"message.id":1}}])

Since your message key is an array you have to first use the $unwind operator and then use the $match operator.

By default mongo will display the _id of the document. So if you do not want to display the _id, after matching the relevant ones, you could use the $project operator

If you don't want the name key to be displayed, simply don't specify the name key in the project part of the query. By default mongo will only display the keys whose value is 1. If the key is not mentioned it will not display it.

And then you use $sort operator, 1 for asecnding and -1 for descending.

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

1 Comment

@tunghk_54 if the answer worked for you, you could mark it right! :)

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.