Search code examples
mongodbmongodb-querymongodb-aggregation

How to sort MongoDB results by element in array that matches a condition?


I have a collection of places which is like this :

{
"_id" : ObjectId("575014da6b028f07bef51d10"),
"name" : "MooD",
.
.
.
"categories" : [
    {
        "categoryList" : [Nightlife, Bar],
        "weight" : 8
    },
    {
        "categoryList" : [Restaurant, Italian Restaurant],
        "weight" : 4
    }
]
}

I want to search in places by a category, for example "Bar". So, I look into categories' categoryList if there is "Bar". After that, I want to sort by the weight of the matched category's weight, so that the above place (where Bar weight is 8) appears before another place where Bar weight is 5.


Solution

  • You have to use aggregation framework. Check this:

    db.mongo.aggregate(
        { $unwind: '$scores' },
        { $match: {
            'scores.categoryList': 'Bar'
        }},
        { $sort: {
            'scores.weight': -1
        }}
    )