0

I have JSON of persons, each person has a list of kids:

{
  "name": ":John",
  "age": 35,
  "kids": [
    {
      "name": "tom",
      "age": 5
    },
    {
      "name": "tina",
      "age": 3
    }
  ]
}

I want to perform findAndModify where the person name is "John" and the kid name is "tina" and update her age to 7.

This is my query so far:

db.people.findAndModify({
    query: { "name" : "John" {--HERE--}},
    update: { $set: { "age" : 7 } }
})

What do I need to replace --HERE-- with to find the kid named "tina"?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
JohnBigs
  • 2,691
  • 3
  • 31
  • 61
  • 4
    I think you should be more concerned about why your daughter is ageing so much quicker than anyone else! – musefan Jul 04 '18 at 14:16
  • @musefan haha, good one :) – JohnBigs Jul 04 '18 at 14:32
  • https://docs.mongodb.com/manual/reference/operator/update/positional/#up._S_ – Alex Blex Jul 04 '18 at 14:39
  • 1
    Possible duplicate of [MongoDB: Updating subdocument](https://stackoverflow.com/questions/5646798/mongodb-updating-subdocument) – Alex Blex Jul 04 '18 at 14:40
  • So according o the dupe mentioned by Alex, does this work: `{ "name" : "John", "kids.name" : "tina" }` with set as `$set: {"kids.$.age": 7}` – musefan Jul 04 '18 at 14:48
  • @musefan it works to help find the document yes, but when i do ```update: { $set: { "age" : 7 } }``` its updating the name of the person, its not updating the child document... – JohnBigs Jul 04 '18 at 14:50
  • @JohnBigs: I updated my comment... though I am just basing my answer from the dupe. I have never used mongodb before :/ – musefan Jul 04 '18 at 14:51
  • 1
    @musefan yes what you wrote in the comment works...:) thanks buddy – JohnBigs Jul 04 '18 at 14:53

1 Answers1

0

Rather than having half an answer in the comments, here is the full example which should do what you need:

db.people.findAndModify({
    query: { "name" : "John", "kids.name" : "tina"},
    update: { $set: { "kids.$.age" : 7} }
})
musefan
  • 47,875
  • 21
  • 135
  • 185