Skip to content

Instantly share code, notes, and snippets.

@delwar2016
Created September 29, 2016 05:34
Show Gist options
  • Save delwar2016/9c929e88edc40da936d56584a6ada8f4 to your computer and use it in GitHub Desktop.
Save delwar2016/9c929e88edc40da936d56584a6ada8f4 to your computer and use it in GitHub Desktop.
mongodb update document
Suppose we have the following document in users_exams collection:
{
"answers" : [
{
"auto_score" : 0,
"question_id" : "579733a97e6b58a0616b2c55",
"user_answers" : "na",
"isCorrect" : false,
"score" : "na",
"user_response" : "",
"uncertain" : false
},
{
"auto_score" : 0,
"question_id" : "5797489c7e6b58a0616b2cfa",
"user_answers" : "na",
"isCorrect" : false,
"score" : "na",
"user_response" : "",
"uncertain" : false
}
],
"exam_markers" : [
{
"marker_id" : ObjectId("55b619321ad1eeb048000017"),
"anonymous" : true,
"assigned_by" : ObjectId("55b619321ad1eeb048000017"),
"path" : "55b619321ad1eeb048000017#55b619321ad1eeb048000017",
"question_ids" : [
"579733a97e6b58a0616b2c55",
"5797489c7e6b58a0616b2cfa"
]
}
]
}
Case 1: we need to update score in a specific question answer, so following query will do that ..
var updateUsersExamAnswerScore = function(paramExamId, paramCallBack){
var question_id = '579749da7e6b58a0616b2d0a'; // we will get id in index 3
var new_score = '10';
var old_score = 'na';
var updatedInfo = { "answers.$.score" : new_score };
db.collection("users_exams").update({
"_id": paramExamId,
"answers.question_id": question_id
},
{
$set: updatedInfo
},
{multi: false}, paramCallBack);
};
Case 2: we need add new marker in exam_markers, so following query will do that ..
var updateUsersExamAppendExamMarker = function(paramExamId, paramCallBack){
var examMarker =
{
"marker_id" : mongoose.Types.ObjectId("55b619321ad1eeb048000018"),
"anonymous" : true,
"assigned_by" : mongoose.Types.ObjectId("55b619321ad1eeb048000017"),
"path" : "55b619321ad1eeb048000017#55b619321ad1eeb048000017",
"question_ids" : [
"579733a97e6b58a0616b2c55",
"5797489c7e6b58a0616b2cfa"
]
};
var updatedInfo = {
"exam_markers":examMarker
};
db.collection("users_exams").update({
"_id": paramExamId
},
{
"$push": updatedInfo
},
{multi: false}, paramCallBack);
};
Case 2: we need add new question to a specific marker in question_ids in exam_markers , so following query will do that ..
var updateUsersExamAppendExamMarkerQuestions = function(paramExamId, paramCallBack){
var examMarkerQuestions = "579733a97e6b58a0616b2c56";
var updatedInfo = {
"exam_markers.$.question_ids": examMarkerQuestions
};
db.collection("users_exams").update({
"_id": paramExamId,
"exam_markers.marker_id": mongoose.Types.ObjectId("55b619321ad1eeb048000018")
},
{
"$push": updatedInfo
},
{multi: false}, paramCallBack);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment