1

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @mickl! Was arrayFilters deprecated in recent MongoDB? I have 4.0.3 and that gives me WriteCommandError({"ok":0,"errmsg":"Unrecognizedfieldinupdateoperation:arrayFilters","code":9,"codeName":"FailedToParse"})
That's weird. I've tried on 4.0.0 and works fine, moreover this example follows the documentation. What MongoDB driver are you using ?
Well I decided not to go down that rabbit hole--I installed 3.6 with brew install [email protected], restarted the service, and updated the featureCompatibilityVersion to 3.6 with db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } ) then could run your command perfectly. Thanks again for your help with this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.