$sort
can only be used after $push
ing 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?
$sort
can only be used after $push
ing 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?
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
},
}
}
},
]
);