| Steps To Reproduce: |
Create collection "test", and insert one document into it:
{
|
{
|
"_id" : NumberLong(1),
|
"pointsBalances" : [
|
{
|
"period" : "2020",
|
"startDate" : ISODate("2020-01-01T00:00:00.000Z"),
|
"endDate" : ISODate("2020-12-31T23:59:59.999Z"),
|
"value" : 0
|
},
|
{
|
"period" : "2019",
|
"startDate" : ISODate("2019-01-01T00:00:00.000Z"),
|
"endDate" : ISODate("2019-12-31T23:59:59.999Z"),
|
"value" : 0
|
}
|
]
|
}
|
Then please perform update - it should work properly:
db.getCollection('test').update(
|
{$and: [ {'_id': 1}, {"pointsBalances.period": '2019'}]},
|
{$set: { "pointsBalances.$.value": 100 } }
|
)
|
Now lets try to update based on dates:
db.getCollection('test').update(
|
{ $and: [ {'_id': 1}, {"pointsBalances.startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}}, {"pointsBalances.endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}} ]},
|
{$set: { "pointsBalances.$.value": 200 } }
|
)
|
Second code updates wrong array element.
Please notice that this behavior only occurs if points balances are not sorted. So in this case it will work properly:
{
|
"_id" : NumberLong(1),
|
"pointsBalances" : [
|
{
|
"period" : "2019",
|
"startDate" : ISODate("2019-01-01T00:00:00.000Z"),
|
"endDate" : ISODate("2019-12-31T23:59:59.999Z"),
|
"value" : 0
|
},
|
{
|
"period" : "2020",
|
"startDate" : ISODate("2020-01-01T00:00:00.000Z"),
|
"endDate" : ISODate("2020-12-31T23:59:59.999Z"),
|
"value" : 0
|
}
|
]
|
}
|
|