0

My collection contains documents of the following form:

        {
          'game_name': 'football',
          'scores': [4,1,2,7,6,0,5]
        }

How do I find the 'scores' of all such objects in the collection and sort them in ascending order?

1 Answer 1

1

If I understand your Question

db.yourcollection.aggregate([

{
    $unwind:"$scores"
},{

    $sort:{
        "scores":1
        }
},{    
        $group:{
            _id:null,
            scores:{$addToSet:"$scores"}
        }
},{

    $project:{
        _id:0,
        scores:1
    }
}

])

Result is:

{
    "result" : [ 
        {
            "scores" : [ 
                7, 
                5, 
                4, 
                6, 
                2, 
                1, 
                0
            ]
        }
    ],
    "ok" : 1
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. Can you please explain $group and $project? I do not know what those are, and $unwind was new for me.
@Rayu sure ! My english is not perfect but i try to explain $unwind Create document for each element of array $group is similar Group of My Sql $project Reshapes a document, and you can decide witch element do you want see, rename and others function like $toLower or $toUpper etc... doc aggregation

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.