Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB aggregate order a nested object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    "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
      }
    ]
  }
]

>Solution :

MongoDB version 5.2 introduced $sortArray operator:

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

Mongo playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading