xennygrimmato
xennygrimmato

Reputation: 2796

MongoDB - Using find() to get values in an array

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?

Upvotes: 0

Views: 39

Answers (1)

Barno
Barno

Reputation: 3331

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
}

Upvotes: 1

Related Questions