0

I´ve read a couple of other posts here on Stackoverflow but havent found any 'general' answer.

Lets say I have a Structure like this:

{
    personsName: "Bob",
    children: [
       {childsName: "Alice", age: "9", weight: "40"}
       {childsName: "Peter", age: "12", weight: "80"} 
    ]
}

Now I want to edit Peters weight because it is actually "45"

I tried:

  .update(
     { personsName: "Bob", children.childsName: "Peter"},
     {
       $set: {children: {weight :"45" } }
     }
   )

For me this should be working...Update the childrens weight to "45" for all children that are named "Peter" and belong to "Bob"... I saw some solutions where they update the array by index, but lets assume we dont know the index, we want to update by the childs property "childsName".

Whats the general way of doing that?

thimos
  • 91
  • 10
  • see https://jira.mongodb.org/browse/SERVER-1243 – Alex Blex Sep 11 '17 at 15:23
  • This looks great, but unfortunately I still use an older version and I dont want to change that in my MEAN-Project. There has to be an option for that on the current version too... – thimos Sep 11 '17 at 16:24
  • If there was, the ticket was not created at the first place. See my answer, if you are happy with limitations of the approach. – Alex Blex Sep 11 '17 at 16:41

1 Answers1

0

If you are sure that Bob has no more than 1 Peter, you can use positional operator as following:

.update(
  { personsName: "Bob", "children.childsName": "Peter"},
  {
    $set: {"children.$.weight" :"45" } 
  }
)

Please note that the operator updates the first matching subdocument only, and only as deep as 1 level.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75