update or add a property to subdocuments of all found documents (MongoDB)

How to update or add a property to subdocuments in MongoDB.

thumbnail for update or add a property to subdocuments of all found documents (MongoDB)

This updateMany finds all agreement_versions that has a participants property on it and sets each member (the $[] selects each individual member) of participants to have a field called role with a value of "Decider".

db.agreement_versions.updateMany(
  {
    participants: {
      $exists: true,
    },
  },
  {
    $set: {
      "participants.$[].role": "Decider",
    },
  }
);

Was this page helpful?

Subscribe to my Newsletter

Every other week I publish the Curiously Crafted newsletter.

In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.

The curious logo of Chase Adams: glasses and a bow tie.stay curious.