My database contains mongo db objects like these:
[{
_id:ObjectId("..."),
subjects:[
{
subjectId: ObjectId("1")
name: "Physics",
marksObtained:80,
rank:0
},
{
subjectId: ObjectId("2")
name: "Chemistry",
marksObtained:70,
rank:0
},
{
subjectId: ObjectId("3")
name: "Maths",
marksObtained:80,
rank:0
}
]
}...]
Now, I am trying to increase rank in Maths of everyone with marks less than 90. For this, I am using the following query:
db.getCollection('test_attempts').updateMany({
"subjects.subjectId": ObjectId("3"),
"subjects.marksObtained":{$lt:90}
},
{
$inc: {
"subjects.$.rank": 1
}
});
This code updates the rank of physics object instead of maths if physics has marksObtained less than 90. At the subject Physics has marks over 90, it updates the object of Chemistry.
Somehow its ignoring subjectId in the query and updating the first object of the array with matching marksObtained condition.
Not sure what I am doing wrong.
P.S. ObjectIds in subjects are for representational purpose only.