1

Problem Statement: The sort option of collection.findAndModify() always updates the lowest value in the given mongoDB documents.

Example Data:

{ "State" : "Florida", "Temperature" : 83 }  
{ "State" : "Florida", "Temperature" : 28 }  
{ "State" : "Florida", "Temperature" : 82 }  
{ "State" : "Any other", "Temperature" : 58 }  
{ "State" : "Florida", "Temperature" : 33 } 

Requirement:
Add month_high:true, against the highest temperature doc.

NodeJS code:

var query = {
  'State': "Florida"
};
var sort = ['Temperature', 'desc']; 
var operator = {
  '$set': {
    'month_high': true
  }
};
var options = {
  'new': true
};

db.collection('readings').findAndModify(query, sort, operator, options, function(err, doc) {
 if (!doc) {
    console.log('no doc');
  } else {
    console.log(doc);
  };
});  

The Result is always same, i.e. the document with lowest temperature gets updated. With above data the result is: { "State" : "Florida", "Temperature" : 28, "month_high" : true }
Now, to check the behavior of sort I have changed it to ascending order as well, but same result, it always picks up the smallest temperature, no matter what the order of the data is before or after sort.

Question:
Can you tell me what and where I am doing it wrong?

1
  • I can use a workaround or two, but I would really like to see findAndModify sort option work. Thanks.
    – Asad Malik
    Sep 25, 2014 at 23:08

1 Answer 1

1

Your sort parameter isn't in the right format. Either of these should work:

var sort = [['Temperature', 'desc']];

OR

var sort = { Temperature: -1 };
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.