简体   繁体   中英

Sort nested array using push in MongoDB?

Consider the query

  EightWeekGamePlan.aggregate(
      [
        {
          $group: {
            _id: {
              LeadId: "$LeadId",
              BusinessName: "$BusinessName",
              PhoneNumberMasque: "$PhoneNumberMasque",
              City: "$City",
              Rooms: "$Rooms",
              dateToString: { format: "%Y-%m-%d", date: "$InserDate" }
            },
            Weeks: {
              $push: {
                Week: "$Week",
                Status: "$Status",
                InsertDate: "$InsertDate"
              },
              // $sort: { Week: 1 }  // doesn't work
            }
          }
        }
      ]

How can I sort the nested array Weeks by Week (it's a number ranging 1-8) ?

I've tried with $sort: { Week: 1 } but the query didn't work out.

Use $sort before $group stage

EightWeekGamePlan.aggregate([
  { $sort: { Week: 1 }},
  { $group: {
    _id: {
      LeadId: "$LeadId",
      BusinessName: "$BusinessName",
      PhoneNumberMasque: "$PhoneNumberMasque",
      City: "$City",
      Rooms: "$Rooms",
      dateToString: { format: "%Y-%m-%d", date: "$InserDate" }
    },
    Weeks: {
      $push: {
        Week: "$Week",
        Status: "$Status",
        InsertDate: "$InsertDate"
      }
    }
  }}
])

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