0

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

Lash
  • 333
  • 1
  • 2
  • 14
  • 1
    Does this answer your question? [Removing null objects from json in mongodb](https://stackoverflow.com/questions/29497382/removing-null-objects-from-json-in-mongodb) – ray May 11 '22 at 19:03
  • `update({},{"$pull": {"color": {"$eq": null}}},{"multi": true})` try this if you are still stuck, i think you need this – Takis May 11 '22 at 19:56

1 Answers1

1

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 ...

R2D2
  • 9,410
  • 2
  • 12
  • 28