0

$sort can only be used after $pushing a new element to an array field. the Goal is to sort after modifying an element of an array during an update call.

How can this be done?

1 Answers1

0

You can use the $push operation with an empty $each modifier to sort an array without adding any elements to it, for example:

db.collection.updateOne(
  {},
  {
    $push: {
      arr: {
        $each: [],
        $sort: 1
      }
    } 
  }
);

To change an element and sort in a single update command, you can do the following, in this example changing the third element of arr to equal 10 and then sorting (added based on comment):

db.collection.updateOne(
  {},
  [
    {
      $set: {
        'arr': {
          $sortArray: {
            input: {
              $concatArrays: [
                { $slice: ['$arr', 2] },
                [10],
                { $slice: ['$arr', 3, { $size: '$arr' }] },
              ]
            },
            sortBy: 1
          },
        }
      }
    },
  ]
);
Aurast
  • 3,189
  • 15
  • 24