2017-08-03 67 views
0

我試圖更新嵌套文件MongoCollection:無法更新嵌套文件

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

的JSON形式如下

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

我嘗試更新的

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

但那麼如果我做

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

我得到

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

爲什麼對象沒有更新?爲什麼我有null

+1

能否請您粘貼一些有效的JSON數據?您的示例數據看起來更像是實體的toString()版本? – dnickless

+0

謝謝,我添加了上面的json格式 – AbtPst

+0

我的更新命令看起來是否合理? – AbtPst

回答

2

您無法通過名爲key(24889)訪問objects所以如果你知道的位置提前,你可以嘗試

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

更好的方法是更新您的文件,其中包括鍵。像

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

和一些使用positional operator

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

`

+1

您在「objects.0」+ innerKey +「.key2」,「val3」 – dnickless

+0

中的數字0後缺少一個點,謝謝!那工作。只是一個小調整,我不得不使用'Updates.set()' – AbtPst

+0

,有沒有類似的方式讓我獲得內部鍵的價值?如果不是更新,我只想獲得價值?我試着把這個和過濾器放在'find()'方法中,但它總是給我整個文檔 – AbtPst