Home > Net >  MongoDB aggregate order a nested object
MongoDB aggregate order a nested object

Time:10-17

In a MongoDB aggerate, is it possible to to sort a nested object and keep it as an object instead of an $unwinded set of records.

EG. Take this collection:

"vehicles": [
  {
    "make": "ford",
    "VehicleImages": [
      {
        "image": "stuff5",
        "ShowOrder": 5
      },
      {
        "image": "stuff2",
        "ShowOrder": 2
      },
      {
        "image": "stuff3",
        "ShowOrder": 3
      },
      {
        "image": "stuff1",
        "ShowOrder": 1
      },
      {
        "image": "stuff4",
        "ShowOrder": 4
      }
    ]
  },
  {
    "make": "vahxhall",
    "VehicleImages": [
      {
        "image": "stuff2",
        "ShowOrder": 2
      },
      {
        "image": "stuff1",
        "ShowOrder": 1
      },
      {
        "image": "stuff4",
        "ShowOrder": 4
      },
      {
        "image": "stuff5",
        "ShowOrder": 5
      },
      {
        "image": "stuff3",
        "ShowOrder": 3
      }
    ]
  }
]

Is it possible to transform it into the following, where the VehicleImages object is ordered by ShowOrder:

    "vehicles": [
  {
    "make": "ford",
    "VehicleImages": [
      {
        "image": "stuff1",
        "ShowOrder": 1
      },
      {
        "image": "stuff2",
        "ShowOrder": 2
      },
      {
        "image": "stuff3",
        "ShowOrder": 3
      },
      {
        "image": "stuff4",
        "ShowOrder": 4
      },
      {
        "image": "stuff5",
        "ShowOrder": 5
      }
    ]
  },
  {
    "make": "vahxhall",
    "VehicleImages": [
      {
        "image": "stuff1",
        "ShowOrder": 1
      },
      {
        "image": "stuff2",
        "ShowOrder": 2
      },
      {
        "image": "stuff3",
        "ShowOrder": 3
      },
      {
        "image": "stuff4",
        "ShowOrder": 4
      },
      {
        "image": "stuff5",
        "ShowOrder": 5
      }
    ]
  }
]

CodePudding user response:

MongoDB version 5.2 introduced $sortArray operator:

db.collection.aggregate([
  {
    $set: {
      VehicleImages: {
        $sortArray: {
          input: "$VehicleImages",
          sortBy: { ShowOrder: 1 }
        }
      }
    }
  }
])

Mongo playground

  • Related