Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB update with sort

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.

like image 262
manojpt Avatar asked Nov 18 '25 13:11

manojpt


1 Answers

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 }
       }
     }
   }
)
like image 99
magiccrafter Avatar answered Nov 21 '25 08:11

magiccrafter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!