Reputation: 599
I am currently working on mongodb for my current project.
{
"_id" : ObjectId("5a168f467cf3661df0df9c11"),
"player_id" : "5a02db1170aaf41013d32747",
"quiz_type" : "Single",
"created_date" : ISODate("2017-11-23T09:05:10Z"),
"questions_answered" : [
{
"question_id" : ObjectId("5a0ac1bfa9897441e038c2f7"),
"player_selection_status" : "Pending",
"time_taken" : 0,
"points_gained" : 0,
"like" : 0
},
{
"question_id" : ObjectId("5a0ac212a9897441e038c2f8"),
"player_selection_status" : "Pending",
"time_taken" : 0,
"points_gained" : 0,
"like" : 0
}
],
"__v" : 0
}
above is my record in player collection, i want to update 2nd of
"questions_answered" : [ {
"question_id" : ObjectId("5a0ac212a9897441e038c2f8"),
"player_selection_status" : "Pending",
"time_taken" : 0,
"points_gained" : 0,
"like" : 0
}
like
"player_selection_status" : "Correct",
"time_taken" : 10,
"points_gained": 5,
"like": 10,
"answered_date":ISODate("2017-11-23T09:05:10Z")
i tried like below
updateData = {questions_answered: {time_taken: 10, like: 1,
answered_date: moment().format()}};
Player_quiz.update({_id: qid, player_id: uid,
"questions_answered.question_id": question_id},
{$set: updateData}).exec();
but it is not worked for me.. please help me out with correct solution ??
Upvotes: 0
Views: 32
Reputation: 3845
db.collection.update({
questions_answered: {
$elemMatch: {
"question_id": ObjectId("5a0ac212a9897441e038c2f8")
}
}
}, {
$set: {
"questions_answered.$.player_selection_status": "Correct",
"questions_answered.$.time_taken": 10,
"questions_answered.$.points_gained": 5,
"questions_answered.$.like": 10,
"questions_answered.$.answered_date": ISODate("2017-11-23T09:05:10Z")
}
}
)
In above mentioned query $elemMatch operator is used to match an element in an array
Upvotes: 0
Reputation: 5466
You have to use a positional operator $ for array update. Here we have questions_answered
as array of documents.
The query to update the document is
db.collection.update(
{"questions_answered.question_id" : ObjectId("5a0ac212a9897441e038c2f8")},
{$set: {
"questions_answered.$.time_taken":10,
"questions_answered.$.player_selection_status" : "Correct",
"questions_answered.$.points_gained": 5,
"questions_answered.$.like": 10,
"questions_answered.$.answered_date":ISODate("2017-11-23T09:05:10Z")
}}
);
Upvotes: 1