0

I am trying to update the nested document

Document{{_id=59837be4324fb01040068109, idKey=2323, objects=[Document{{24889=Document{{key1=val1, key2=val2}}}}]}}

the json form looks like this

{
    "_id": "59837be4324fb01040068109",
    "idKey": 2323,
    "objects": [{
        "24889": {
            "key1": "val1",
            "key2": "val2"
        }
    }]
}

i tried to update as

String innerKey="24889";
mongoCollection.updateOne(eq("idKey", 2323),new Document("$set", new Document("objects."+innerKey+".key2", "val3")));

but then if i do

Document updatedDoc = mongoCollection.find(eq("idKey", 2323)).first();

i get

Document{{_id=59837be4324fb01040068109, idKey=2323, objects=[Document{{24889=Document{{key1=val1, key2=val2}}}}, null, null, null, null, null, null, null, ...

why did the object not get updated? and why do i have the nulls?

3
  • 1
    Could you please paste some valid JSON data? Your sample data appears to be more like a toString() version of your entities? Commented Aug 3, 2017 at 20:11
  • thanks, i added the json format above Commented Aug 3, 2017 at 21:07
  • does my update command look reasonable? Commented Aug 3, 2017 at 21:09

1 Answer 1

2

You can't access objects by named key (24889) so if you know the position beforehand you can try

mongoCollection.updateOne(eq("idKey", 2323),new Document("$set", new Document("objects.0."+innerKey+".key2", "val3"))); 

Better approach would be to update your document to include keys. Something like

{
  "_id": "59837be4324fb01040068109",
  "idKey": 2323,
  "objects": [
    {
      "name": "24889",
      "value": {
        "key1": "val1",
        "key2": "val2"
      }
    }
  ]
}

and use positional operator

mongoCollection.updateOne(and(eq("idKey", 2323), eq("objects.name", innerKey)),set("objects.$.value.key2", "val3"));

`

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

4 Comments

You're missing a dot after the number 0 in "objects.0"+innerKey+".key2", "val3"
thanks! that worked. just a minor tweak, i had to use Updates.set()
by the way, is there a similar way for me to get the value of an inner key? what if instead of update, i just want to get the value? I tried putting the and filter in the find() method but it always gave me teh entire document
You are welcome. I should have noted that I statically imported the Updates class to use set method for your earlier comment. I don't think it is possible in first case but you can use something like for second case mongoCollection.find(and(eq("idKey", 2323), eq("objects.name", innerKey))).projection(Projections.include("objects.$")) and pick the inner value in the application code.

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.