I don't know whether this question has been asked before. However, I need to ask this to get help from you guys:
I have a document like below:
{
"taskboard_id": "6149a3de8f604511e6883bae",
"user_id": "61399af5d6294f56aa1116f0",
"task_groups": [{
"task_group_id": "614975a0e8fad7ef68561b36",
"task_id": "614869a706ff00ab459460e5",
"is_completed": true,
"completion_date":"2021-10-07T05:04:50.760Z",
},
{
"task_group_id": "614975a0e8fad7ef68561b37",
"task_id": "614869a706ff00ab459460e5",
"is_completed": false,
"completion_date":"",
}]
}
The difference between the array of two objects is the task_group_id
.
Now I want to update the is_completed
and completion_date
by taskboard_id
, user_id
, "task_groups.task_group_id"
and "task_groups. task_id"
. And below is my query:
db.task_status.updateOne(
{
user_id: new ObjectId(payload.user_id),
taskboard_id: new ObjectId(payload.taskboard_id),
"task_groups.task_group_id": new ObjectId(payload.task_group_id),
"task_groups.task_id": new ObjectId(payload.task_id),
},
$set: {
"task_groups.$.is_completed": payload.is_completed,
"task_groups.$.completion_date": new Date(),
},
);
The problem is whenever I try to update the first object is updated fine but whenever it comes to the second one it doesn't update. Can anyone help me with this?
CodePudding user response:
use arrayfilter
in update
db.collection.update({
user_id: "61399af5d6294f56aa1116f0",
taskboard_id: "6149a3de8f604511e6883bae",
"task_groups.task_group_id": "614975a0e8fad7ef68561b37",
"task_groups.task_id": "614869a706ff00ab459460e5",
},
{
"$set": {
"task_groups.$[item].is_completed": true,
"task_groups.$[item].completion_date": new Date(),
}
},
{
arrayFilters: [
{
"item.task_group_id": {
$eq: "614975a0e8fad7ef68561b37"
},
"item.task_id": {
$eq: "614869a706ff00ab459460e5"
}
}
],
multi: true
})