1

How do I change the ans to other int and increase retry by 1 in courseList.quizScore on an update statement in mongodb with meteorjs?

Below is my query which is not working I am using $set, is this the correct operate to use? Can i use $set and $inc in the one update statement?

collection.jsx

Meteor.users.update({
    _id: Meteor.userId(),
    "courseList.courseId": courseId,
    "courseList.quizScore.qnNum": qnNum,
}, {
    $set: {
        "courseList.quizScore.$.ans": selectedAns
    }
})

mongoDB

{
  "_id": "yo8Mi2jKtoNSzgLDL",
  "courseList": [
    {
      "courseId": "nJmu5HW7g3wjWo47P",
      "classId": "3RniSRC3NurDRwZ2x",
      "quizScore": [
        {
          "qnNum": 0,
          "ans": 0,
          "retry": 1
        },
        {
          "qnNum": 1,
          "ans": 0,
          "retry": 1
        }
      ],
      "status": "Not Started"
    },
    {
      "courseId": "5ge2grte3wjWo4rh",
      "classId": "bffbeRC3NurDRtbf",
      "quizScore": [
        {
          "qnNum": 0,
          "ans": 1,
          "retry": 1
        },
        {
          "qnNum": 1,
          "ans": 2,
          "retry": 3
        }
      ],
      "status": "Not Started"
    }
  ]
}

1 Answer 1

1

There is an array within an array in your data, there is no easy way to reference the nested sub-array quizScore unless you know the position in this sub-array you want to update.

You can access the outer array courseList through $, and to access the inner array quizScore through position. Here is one sample code to update the first element of quizeScore matching courseId through using $set and $inc in one update statement.

Meteor.users.update(
          {_id: Meteor.userId(), 
          'courseList.courseId': courseId}, 
          {$set: {'courseList.$.quizScore.0.ans': selectedAns}, 
           $inc: {'courseList.$.quizScore.0.retry': 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.