简体   繁体   中英

MongoDB Get highest value for each date and put them into an array

What's the best way to go about getting the highest "score" for each "date" and storing them into an array. Let's the say there are over 50 scores for any particular date.

The database looks like this

 {
   "_id" : ObjectId("5c06b91b583248493294"),
   "classid" : "00010109e2",
   "score" : 720,
   "height" : 1440,
   "time" : "2018-11-27T18:05:13.297621823Z",
   "__v" : 0
 }

And what I'm trying to do is get the highest score for each date, from a date-range of around 2 weeks and store one highest score for each date in a simple array.

I've tried loads of things, including recursion to no avail.

Can anyone shed any light on this, or point me in the right direction?

You should look into mongodb aggregation and especially $group operator, it usually used to perform such kind of operations.

In this case your code will look like that:

Scores.aggregate([
  {
    $match: {
      time: {
        $gte: startOfSomePeriod,
        $lte: endOfSomePeriod
      }
    }
  },
  {
    $group: {
      _id: {
        year: { $year: "$time" },
        month: { $month: "$time" },
        day: { $dayOfMonth: "$time" }
      },
      score: { $max: "$score" }
    }
  }
]);

PS You can use mongooses default createdAt timestamp by simply adding an option to your schema definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM