3

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.

styvane
  • 59,869
  • 19
  • 150
  • 156
manojpt
  • 1,179
  • 2
  • 12
  • 20
  • this would help : http://docs.mongodb.org/manual/reference/operator/update/sort/#sort-array-elements-that-are-not-documents – Dev May 21 '15 at 13:37
  • 1
    how are you updating this document? It would be better if you share code for that. – Dev May 21 '15 at 13:52
  • @user3805045 did you take a look at [`$sort`](http://docs.mongodb.org/manual/reference/operator/update/sort/)? – bagrat May 23 '15 at 08:20
  • 1
    @ n9code yes i have. I used $sort to push objects. But the case here is not push, the problem I am facing in updating existing one with sort functionality. – manojpt May 23 '15 at 08:56

2 Answers2

1

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 }
       }
     }
   }
)
magiccrafter
  • 5,175
  • 1
  • 56
  • 50
0

MongoDB allow to updated nested documents using $elemMatch and using $ operator so you can update year as below :

db.collectionName.update({"somearray":{"$elemMatch":{"year":2012}}},{"$set":{"somearray.$.year":2014}}) 

This query updated the year 2012 to 2015 but array positioned not changed.But if you want still to changed array positioned with updated values then you should used some programming logic or code I write this script which will update array and pushed with sorted

function compare(a, b) {
  if(a.year > b.year) return -1;
  if(a.year < b.year) return 1;
  return 0;
}
var givenYear = 2012; // which year you want to update
var array = []; // empty array to push data 
db.collectionName.find().forEach(function(data) {
  var objects = data.somearray;
  for(var i = 0; i < objects.length; i++) {
    if(data.somearray[i].year == givenYear) {
      array.push({
        "year": 2014
      });
    } else {
      array.push({
        "year": data.somearray[i].year
      });
    }
  }
  var sortedArray = array.sort(compare); // pass to compare function to sort the array with year
  db.collectionName.update({
    "_id": 1,"somearray":{"$elemMatch":{"year":2012}} //match criteria
  }, {
    "$set": {
      "somearray": sortedArray // updated whole array with new sorted array
    }
  });
}) 

Note : compare function ref

Community
  • 1
  • 1
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
  • Are you sure that user3805045 uses JavaScript as a language? And by this are you stating that sorting on client side, and then updating a whole array is better than making two separate updates? Pretty much ridiculous :) – bagrat May 22 '15 at 14:03
  • 1
    @n9code here I give another approach how should match and sort array. I don't know what user3805045 use java script or not but I explain here another way to update and more important after every update mongodb update every index associated with the collection in addition to the data itself [here](http://docs.mongodb.org/manual/core/write-performance/), avoiding this index update mongoDB introduced bulk update. So it's better way to update documents in one request. – Neo-coder May 22 '15 at 15:23
  • aha, and in your case you have to fetch the whole array out of MongoDB, make the update on client side, sort on client side and send the whole array back. – bagrat May 22 '15 at 15:35
  • Actually I wanted it in Java. Javascript solution may help some one else. i understood that get the data, sort it and then update using set. – manojpt May 23 '15 at 07:39