Update null field become array

I have collection like this:

[
  {
    "_id": 1,
    "linkedId": null
  },
  {
    "_id": 2,
    "linkedId": [1]
  }
]

I try to update the data to insert an item on the array using this query:

db.collection.update({
  _id: 2
},
{
  "$addToSet": {
    "linkedId": 3
  }
})

this query works for _id:2 but error for _id:1 since $addToSet will be error for non-array field. How can I make the linkedId become array if it null then add non-duplicate item on it using single operation?
Thank you on advance

The best thing is to permanently migrate your linkedId:null to an empty array.

Another solution is to update with aggregation that species 2 different update based of the current state of linkedId.

1 Like

@Edi_Krisnayana, thanks for the followup.

Hi @steevej Thank you for the suggestion.
That’s what I do for now, I use 2 different update operations. But I wondering if there is a single update operation for that.

1 Like

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

Exactly.

The square brackets in the update part of update() indicate

The then: and else: are

with the $cond…/$linkedId being

Thanks, @Akshat_Gupta3 for sharing a concrete implementation which should be marked as the solution.

Thank you for sharing @Akshat_Gupta3 , that’s really helpful.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.