caeus
caeus

Reputation: 3696

how to modify every field of a nested document mongo?

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

Upvotes: 0

Views: 53

Answers (1)

YuTing
YuTing

Reputation: 6629

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

mongoplayground

Upvotes: 2

Related Questions