0

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.

Manolis Karamanis
  • 758
  • 1
  • 10
  • 27
  • 1
    Would an aggregation work in your situation? http://stackoverflow.com/questions/13449874/how-to-sort-array-inside-collection-record-in-mongodb – JPitts Jul 13 '16 at 12:17

1 Answers1

2

You have to use aggregation framework. Check this:

db.mongo.aggregate(
    { $unwind: '$scores' },
    { $match: {
        'scores.categoryList': 'Bar'
    }},
    { $sort: {
        'scores.weight': -1
    }}
)
Glib Martynenko
  • 128
  • 1
  • 9
  • This works. Thank you very much for the response. In your query above I believe scores is meant to be categories. The problem now is that I cannot get the rest of the categories in the response. In my question's example I would also like to get the Restaurant category of that place. Have you anything in mind? Thank you in advance. – Manolis Karamanis Jul 13 '16 at 16:13
  • I am not sure that I am understand you correct.... Try this code: db.mongo.aggregate( { $project : { "scores.categoryList" : 1 , "scores.weight" : 1, "_id" : 0} }, { $unwind: '$scores'}, { $unwind: '$scores.categoryList'}, { $sort: { 'scores.weight': -1 }} ) – Glib Martynenko Jul 13 '16 at 18:10
  • I am recommend you go to MongoDB University page (https://university.mongodb.com/) and take one of the courses. They are free and very helpful. – Glib Martynenko Jul 13 '16 at 18:19