0

I want to update a set of array of object using date range. I did below query

Person.update({'data.date': {'$gte': '1-1-2016', '$lte': '1-5-2016'}}, 
    {'$set': {'data.$.score':1000}}, 
    {multi:true})

Turned out the score on date 1-1-2016 only been updated, something is wrong with the $lte?

This is my schema

var Person = new Schema({
    name: String,
    data: [{
        date: Date,
        score: Number
    }]
});
Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

1 Answers1

0

I just realized it's because of the positional operator $. According to the MongoDB docs:

Remember that the positional $ operator acts as a placeholder for the first match of the update query document.

https://docs.mongodb.com/manual/reference/operator/update/positional/

In your case only the first embedded document is being updated because that is the behaviour of the positional operator.

You could use these answers as a reference:

Multiple use of the positional `$` operator to update nested arrays

Multiple update of embedded documents' properties

Community
  • 1
  • 1
Antonio Val
  • 3,200
  • 1
  • 14
  • 27
  • what? what is the answer for this question? what is the problem? please be specified. – Jenny Mok Dec 31 '16 at 10:02
  • I just expanded the explanation, because of the behaviour of the positional operator only your first embedded document is being updated. – Antonio Val Dec 31 '16 at 10:05
  • so any solution for this? means I can't update mutliple docs using gte and lte?? Hmm I expect multi:true is used for that. – Jenny Mok Dec 31 '16 at 10:18
  • `multi: true` is used through multiple documents, not through embedded documents inside the same document (it does not have any effect). It seems there is not a direct solution for these cases, take a look to the answers I posted. – Antonio Val Dec 31 '16 at 10:38
  • I think I have to look and execute my above query. – Jenny Mok Dec 31 '16 at 13:10