rid
rid

Reputation: 63560

How can I $unset a sub-document that's part of another sub-document in MongoDB?

I have a collection containing documents of the following form:

{
  tokens: {
      name: {
          value: "...",
      },
      ...
  }
}

name can be anything, and there can be multiple embedded documents assigned to different keys, all of which have a value field.

How do I $unset all embedded documents that have a certain value? { $unset: { "tokens.value": "test" } } doesn't work, and nor does "tokens.$[].value" or "tokens.$.value".

Upvotes: 0

Views: 95

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can use pipelined form of update, like this:

db.collection.update({},
[
  {
    "$set": {
      "tokens": {
        $arrayToObject: {
          "$filter": {
            "input": {
              "$objectToArray": "$$ROOT.tokens"
            },
            "as": "item",
            "cond": {
              "$ne": [
                "$$item.v.value",
                "test"
              ]
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Playground link.

In this query, we do the following:

  1. We convert tokens object to an array, using $objectToArray.
  2. We filter out the array elements which have a value key present in embedded documents and have a value of test using $filter.
  3. Finally we convert the filtered array back again to object, and assign it to tokens key.

Upvotes: 1

Related Questions