0

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?

3
  • maybe db.restaurants.find({borough: "Brooklyn"}).sort( {date :1} ) ? Commented Jun 21, 2019 at 17:22
  • @JoeA I'm trying to sort by grades.score instead of grades.date. So do you think db.restaurants.find({borough: "Brooklyn"}).sort( {score: -1} ) would work? Commented Jun 21, 2019 at 18:52
  • you can try it defintley! Since that would be descending order. Commented Jun 21, 2019 at 18:55

1 Answer 1

1

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});
Sign up to request clarification or add additional context in comments.

3 Comments

The first item in "grades" is always the latest one, so sorting them by the first "grade" in grades would suffice. Is it possible to do like array indexing, where "grades.grade"[0] would do the trick?
Yes it would actually, i edited my answer to reflect this condition. also considering this ,indexing only the array at index 0 would create a much smaller and efficient index.
Thank you! I just tried it and this works flawlessly!

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.