Sample document looks like this:
{
_id: 1,
"somearray":
[
{
year: 2013
},
{
year: 2012
},
{
year: 2011
},
{
year: 2010
}
]
}
The array "somearray" is sorted. Suppose if I update the second object {year : 2012} to {year : 2014}, is it possible to sort the array. the expected output after update is below:
{
_id: 1,
"somearray":
[
{
year: 2014
},
{
year: 2013
},
{
year: 2011
},
{
year: 2010
}
]
}
Could any one help.
It is worth checking the mongo's $sort modifier. Introduces since version 2.4.
Here is the link to the reference: https://docs.mongodb.com/manual/reference/operator/update/sort/
The following example will just trigger the sort
db.collection.update(
{ _id: 1 },
{
$push: {
somearray: {
$each: [],
$sort: { year: -1 }
}
}
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With