Option 1: using aggregation pipeline inside update() query with $filter
db.collection.update({
color: {
$exists: true,
$eq: null
}
},
[
{
$addFields: {
color: {
$filter: {
input: "$color",
as: "c",
cond: {
$ne: [
"$$c",
null
]
}
}
}
}
}
],
{
multi: true
})
Explanation:
- Match only documents where array color exist and contain at least single null value
- Replace the color array with same with no null values
- Add {multi:true} to apply to all found documents
playground
Option 2: remove all null elements in color array with $pull
db.collection.update({
color: {
$exists: true,
$eq: null
}
},
{
$pull: {
color: null
}
},
{
multi: true
})
Explanation:
- Match all documents having color array and at least single null element.
- Remove (
$pull) all null color array elements
- Apply to all matched documents (
multi:true)
playground
I would use the option 2 since it looks simple, but in certain cases for bigger collections, the $pull operation may perform slower so is better to test ...
update({},{"$pull": {"color": {"$eq": null}}},{"multi": true})try this if you are still stuck, i think you need this