0

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.

1 Answer 1

1
"subjects.subjectId": ObjectId("3"),
"subjects.marksObtained":{$lt:90}

The above query will search fields (subjectId, marksObtained) in different documents,

Try $elemMatch operator to match both the fields in same document,

db.getCollection('test_attempts').updateMany({
  subjects: {
    $elemMatch: {
      subjectId: ObjectId("3"),
      marksObtained: { $lt:90 }
    }
  }
},
{
  $inc: {
    "subjects.$.rank": 1
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.