2

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Chique
  • 735
  • 3
  • 15

1 Answers1

3

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46