Conditional update Object vs Array

I am having issues adding fields to an existing field. It is either an Object with a value or an array with one or more values. I want to change all fields to an array with three fields and retain the existing values.
My aggregate attempt returns the Error: need an update object or pipeline.

I want to go from this:
roles: “automation_engineer”
or
roles:
0:“mentor”
1:“automation_engineer”

to this:
roles:
0: name: “mentor”
startDate: “01-01-2000”
endDate: “01-01-2099”

This is my code that fails:

db.test.update(
   {  $project: {
          roles: {
              $cond: {
                  "if": {
                      $isArray: '$roles'
                  },
                  "then": {
                     $set: {
                       roles: {
                         $map: {
                           input: "$roles",
                           in: {
                             name: "$$this",
                             "startDate": "Jan 1 2000",
                             "endDate": "Jan 1 2099"   
                           }
                         }
                       }
                     }
                   },
                  "else": {  
                     $set: {
                     roles: [ {
                         "name" : {$ifNull: ["$roles", null] },
                         "startDate": "Jan 1 2000",
                         "endDate": "Jan 1 2099"     
                         }
                     ] }
                  }
              }
          }
      }
  }
)

Thanks,
Austin

Because the syntax is wrong.

When doing an update you need to specify 2 parameters. The first one is a query that specifies which documents to update. The second parameter is the update operation.

You are missing the query part.

1 Like