2

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

2
  • 1
    Does this answer your question? Removing null objects from json in mongodb Commented May 11, 2022 at 19:03
  • update({},{"$pull": {"color": {"$eq": null}}},{"multi": true}) try this if you are still stuck, i think you need this Commented May 11, 2022 at 19:56

1 Answer 1

2

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:

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.