SamTulster
SamTulster

Reputation: 79

How to sort element in array of arrays in MongoDB?

I'm learning MongoDB's sorting. I have a collection with documents that look like this:

{
"_id" : ObjectId("5d0c13fbfdca455311248d6f"),
"borough" : "Brooklyn",
"grades" : 
    [ 
        { "date" : ISODate("2014-04-16T00:00:00Z"), "grade" : "A", "score" : 5 },
        { "date" : ISODate("2013-04-23T00:00:00Z"), "grade" : "B", "score" : 2 },
        { "date" : ISODate("2012-04-24T00:00:00Z"), "grade" : "A", "score" : 4 }
    ],
"name" : "C & C Catering Service",
"restaurant_id" : "40357437"
}

And I want to sort all restaurants in Brooklyn by their most recent score.

Right now I have:

db.restaurants.find({borough: "Brooklyn"}).sort()

But I don't know how to proceed. Any help on how to sort this by most recent score, which is the first entry in grades?

Upvotes: 0

Views: 297

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22276

This is not possible in mongo with a find query, you'll have to use an aggregation like this one:

db.collection.aggregate([
  {
    $unwind: "$grades"
  }, 
  {
    $sort: {"grades.date": -1}
  }, 
  {
     $group: {
        _id:"$_id",
        grades: {$push:"$grades"},
        resturant_id: {$first: "$resturant_id",
        name: {$first: "$name"}, 
        borough: {$first: "$borough"}
    }
  }
]);

EDIT:

 collection.find({}).sort({'grades.0.date': -1});

Upvotes: 1

Related Questions