0

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

1 Answer 1

1

MongoDB version 5.2 introduced $sortArray operator:

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

Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.