w3resource

MongoDB Exercise - Find the restaurant with the most recent grade date


Write a MongoDB query to find the restaurant with the most recent grade date.

Structure of 'restaurants' collection :

{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}

Query:

db.restaurants.aggregate([
{ $unwind: "$grades" },
{ $sort: { "grades.date": -1 } },
{ $limit: 1 },
{ $project: { name: 1, "grades.date": 1, _id: 0 } }
])

Output:

{
grades: { date: ISODate("2015-01-20T00:00:00.000Z") },
name: 'Ambassador Diner'
  }

Explanation:

The said query in MongoDB retrieves the restaurant with the most recent grade date, and return the name of the restaurant and the date of the most recent grade.

The $unwind operator, which creates a new document for each element in the grades array.

The $sort operator, which sorts the documents in descending order based on the grades.date field. This means that the most recent grade will appear first in the result set.

The $limit operator will limit the result set to only the first document, which will be the restaurant with the most recent grade date.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Find all the Chinese restaurants in Brooklyn.
Next: Find the top 5 restaurants for each cuisine type, along with their average score.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.