0
{
id:1,
projectName:'Project1'
start:"17-04-2022",
end:"12-05-2020",
tasks:[
{
taskId:1,
taskName:'first task',
taskStart:'20-04-2022',
taskEnd:'25-04-2022'
},

{
taskid:2,
taskName:'second task',
taskStart:'25-04-2022',
taskEnd:'30-04-2022'
},

]
},
{
id:2,
projectName:'Project2'
start:"27-04-2022",
end:"22-05-2020",
tasks:[
{
taskId:1,
taskName:'first task',
taskStart:'30-04-2022',
taskEnd:'12-05-2022'
},

{
taskid:2,
taskName:'second task',
taskStart:'28-04-2022',
taskEnd:'15-05-2022'
},

]
}

how to update field "taskEnd" of tasks array with document id=1 and taskID=1 AND while updating if data from the frontend which is used to update the "taskEnd" exceeds "end" field, update the "end" field also with same value.

Thanks in Advance,

I know how to update specific field for the array of objects and conditional update of field with two separate queries.

can it be done with single query?

1 Answers1

0

You can do this with a pipeline update instead of using an update document. I'm assuming you are getting the input date in the same format as the other dates.

var input_date = "11-05-2020";
db.collection.update({
  id: 1
},
[
  {
    $addFields: {
      end: {
        $cond: [
          {
            $gt: [
              {
                $dateFromString: {
                  dateString: "$end"
                }
              },
              {
                $dateFromString: {
                  dateString: input_date 
                }
              }
            ]
          },
          "$end",
          input_date 
        ]
      },
      tasks: {
        $map: {
          input: "$tasks",
          as: "elem",
          in: {
            $cond: [
              {
                $eq: [
                  "$$elem.taskId",
                  1
                ]
              },
              {
                $setField: {
                  field: "taskEnd",
                  input: "$$elem",
                  value: input_date 
                }
              },
              "$$elem"
            ]
          }
        }
      }
    }
  }
])
Blue Star
  • 1,932
  • 1
  • 10
  • 11