Update null field become array

Hi @Edi_Krisnayana ,
Completely agree to what @steevej mentioned, but if still you need a single query for your use case then you have something like this -

db.collection.update({
  _id: 1
},
[
  {
    $set: {
      linkedId: {
        $cond: {
          if: {
            $eq: [
              "$linkedId",
              null
            ]
          },
          then: [
            3
          ],
          else: {
            $cond: {
              if: {
                $in: [
                  3,
                  "$linkedId"
                ]
              },
              then: "$linkedId",
              else: {
                $concatArrays: [
                  "$linkedId",
                  [
                    3
                  ]
                ]
              }
            }
          }
        }
      }
    }
  }
])
1 Like