Home > Mobile >  how to modify every field of a nested document mongo?
how to modify every field of a nested document mongo?

Time:03-31

so imagine I have the following document:

{
  "_id":...,
  "data":{"a":[],"b":[],"x":[]}
}

I don't know beforehand which fields the subdocument data may have. I just know that every field in that subdocument will be an array

How do I make an update so that the object results like:

{
  "_id":...,
  "data":{"a":[1],"b":[1],"x":[1]}
}

Constraint: Using only mongodb operators. One single update. Without knowing the fields inside the 'data' subdocument

CodePudding user response:

db.collection.update({},
[
  {
    $set: {
      data: {
        $arrayToObject: {
          $map: {
            input: { $objectToArray: "$data" },
            as: "d",
            in: { k: "$$d.k", v: [ 1 ] }
          }
        }
      }
    }
  }
])

mongoplayground

CodePudding user response:

db.collection.update({}, { $set: {"data.$.a": [1]} })
db.collection.update({}, { $set: {"data.$.b": [1]} })
db.collection.update({}, { $set: {"data.$.x": [1]} })
  • Related