Home > Mobile >  Removing null values from array object mongodb
Removing null values from array object mongodb

Time:05-12

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:

  1. Match only documents where array color exist and contain at least single null value
  2. Replace the color array with same with no null values
  3. Add {multi:true} to apply to all found ducuments

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
})

Explained:

  1. Match all documents having color array and at least single null element.
  2. Remove ( $pull) all null color array elements
  3. 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 ...

  • Related