MongoDB: How to remove a property from all objects in array?

86 Views Asked by At

I want to unset a property from all items in an array of objects in MongoDB.

Playground Link


Explanation:

Suppose I have an array of objects with the following structure in a document:

{
    "key": 1,
    "questions": [
      {
        "text": "Q1",
        "explanation": "Howdy?"
      },
      {
        "text": "Q2",
        "explanation": "Pizza"
      }
    ]
}

I want to remove the property explanation from all the objects in the questions array.

How can I achieve that?

I was hoping something like the following would work:

db.collection.update({},
{
  $unset: {
    "questions.explanation": 1
  }
})

But it seems to have no effect.

1

There are 1 best solutions below

0
Yong Shun On BEST ANSWER

You need the $[] all positional operator to remove the field from all elements in the array.

db.collection.update({},
{
  $unset: {
    "questions.$[].explanation": 1
  }
})

Demo @ Mongo Playground