How can I remove null elements from this array with updateMany? I have many documents following this pattern with null values and I want to update them all without null values.
{
"car": "Honda",
"color": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
"red",
"orange"
]
}
I tried
db.db_urls.updateMany({color: null}, { $unset : { color: 1 }})
but it is removing the contents of all fields
CodePudding user response:
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
})
Explained:
- 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 ducuments
Option 2. Remove all null elements in color array with $pull:
db.collection.update({
color: {
$exists: true,
$eq: null
}
},
{
$pull: {
color: null
}
},
{
multi: true
})
Explained:
- 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 )
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 ...