duhaime
duhaime

Reputation: 27611

MongoDB: Updating Within Nested Array

I have a beautiful little MongoDB collection with the following object:

{
  "_id" : ObjectId("5919df60adb8170833fb4fa9"),
  "a" : [
    {
      "_id" : ObjectId("5919df60adb8170833fb4faa"),
      "b" : {
        "c" : true,
        "d" : [
          {
            "e" : "cats",
          },
          {
            "f" : "dogs",
          }
        ]
      }
    }
  ]
}

One can set this up by running mongo then running the following commands:

use cats
db.wonk.insertOne({"_id":ObjectId("5919df60adb8170833fb4fa9"),"a":[{"_id":ObjectId("5919df60adb8170833fb4faa"),"b":{"c":true,"d":[{"e":"cats",},{"f":"dogs",}]}}]})

I want to set the value of ‘e’ to ‘meow’, but can’t figure out how to query up that object. I thought the following would find e but no dice:

db.wonk.find({a: {  $elemMatch: { 'b': { 'd': { $elemMatch: { 'e': 'cats'  }  }  }  }  }})

My question is: how can I set the value of e to meow? Any help others can offer on this question would be hugely appreciated!

Upvotes: 1

Views: 45

Answers (1)

mickl
mickl

Reputation: 49985

You can use positional filtered operator here:

db.wonk.update({ "_id":ObjectId("5919df60adb8170833fb4fa9") }, 
    { $set: { "a.$[doc1].b.d.$[doc2].e": "meow" } }, 
    { arrayFilters: [ { "doc1._id": ObjectId("5919df60adb8170833fb4faa")  }, { "doc2.e": "cats" } ] })

doc1 and doc2 are simply kind of placeholders that can be then used inside arrayFilters to define conditions that are used by MongoDB when traversing your document.

Upvotes: 2

Related Questions