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", [] ] } ] } } }
])
CodePudding user response:
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.