Reputation: 1269
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.
Upvotes: 3
Views: 8018
Reputation: 5474
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 }
}
}
}
)
Upvotes: 1
Reputation: 7840
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
Upvotes: 0