简体   繁体   中英

Mongoose: How to sort aggregate response with two fields

I have this mongoose query:

 MinutesSpentStudying.aggregate([
    { $match: { connected_user_id: ObjectId(user_id) } },
    {
      $project: {
        minutes_spent_studying: 1,
        year: { $year: "$date" },
        day: { $dayOfMonth: "$date" },
      },
    },
    {
      $group: {
        _id: {
          day: "$day",
          year: "$year",
        },
        total_minutes: { $sum: "$minutes_spent_studying" },
      },
    },
    { $sort: { _id: 1 } },
  ]);

It returns this response:

[
    {
        "_id": {
            "day": 2,
            "year": 2021
        },
        "total_minutes": 11
    },
    {
        "_id": {
            "day": 3,
            "year": 2021
        },
        "total_minutes": 1
    },
    {
        "_id": {
            "day": 26,
            "year": 2020
        },
        "total_minutes": 1
    },
    {
        "_id": {
            "day": 27,
            "year": 2020
        },
        "total_minutes": 3
    },
]

I'd like it to sort out by year, and then by day so that it returns the results of 2020 and then the result of 2021.

Any idea how to configure so as to achieve this result?

You can sort by multiple fields and use the dot notation for the nested ones:

{
    $sort: {
        "_id.year": 1,
        "_id.day": 1
    }
}

Mongo Playground

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