1

mongo playground

I want to sort the views from biggest to smallest inside for each category. How to sort this?

So the expected outcome should be like this:

[
  {
    "_id": "101",
    "cars": [
      {
        "carName": "CyberTruck",
        "driverId": "202",
        "views": 50
      },
      {
        "carName": "Model 3",
        "driverId": "202",
        "views": 40
      },
      {
        "carName": "Model x",
        "driverId": "202",
        "views": 30
      }
    ],
    "categoryName": "Tesla"
  },
  {
    "_id": "102",
    "cars": [
      {
        "carName": "X1",
        "driverId": "201",
        "views": 20
      }
    ],
    "categoryName": "BMW"
  }
]
potato
  • 203
  • 2
  • 15
  • 1
    Here is a similar post and answer: [Mongodb sort inner array](https://stackoverflow.com/questions/15388127/mongodb-sort-inner-array) >note there are two answers, (1) Uses a MongoDB version prior to 4.4 aggregation, (2) Uses a 4.4 version aggregation with `$function` operator. – prasad_ Dec 03 '20 at 09:31
  • @prasad_ Thanks! I solved by your reference but how can I also project my categoryName? The categoryName was lost when using $group. https://mongoplayground.net/p/MsF_enDXaY7 – potato Dec 03 '20 at 09:45
  • I solved: https://mongoplayground.net/p/FPCU4aV9a9X – potato Dec 03 '20 at 10:07

0 Answers0