2

I want to replace an array field in document that has value of null to an empty array []. I tried this query but it's not working. Please help.

Basically I want testArray: null to be testArray: []

db.myTestCollection.aggregate( { "_id": ObjectId('1120191011212112') },
   [ { $set: { testArray: { $ifNull: [ { $concatArrays: [ "$testArray", [] ] } ] } } }
])

1 Answer 1

2

Looks like you mostly have a syntax error. But you can also move the $ifNull logic into the filter predicate as well so that no update is considered/applied if the existing testArray field isn't already null. So:

db.collection.update({
  _id: 1,
  "testArray": null
},
[
  {
    $set: {
      testArray: []
    }
  }
])

Working playground example here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.