我目前正在为当前的项目工作mongodb。
{
"_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
}
以上是我在玩家收藏中的记录,我想更新第二个
"questions_answered" : [ {
"question_id" : ObjectId("5a0ac212a9897441e038c2f8"),
"player_selection_status" : "Pending",
"time_taken" : 0,
"points_gained" : 0,
"like" : 0
}
像
"player_selection_status" : "Correct",
"time_taken" : 10,
"points_gained": 5,
"like": 10,
"answered_date":ISODate("2017-11-23T09:05:10Z")
我试过以下
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();
但它对我不起作用..请帮我解决正确的问题?
答案 0 :(得分:1)
您必须使用positional operator $进行阵列更新。这里我们有questions_answered
作为文档数组。
更新文档的查询是
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")
}}
);
答案 1 :(得分:0)
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")
}
}
)
在上面提到的查询 $ elemMatch 运算符用于匹配数组中的元素