我正在尝试更新嵌套文档
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
s?
答案 0 :(得分:2)
您无法通过命名密钥(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"
}
}
]
}
mongoCollection.updateOne(and(eq("idKey", 2323), eq("objects.name", innerKey)),set("objects.$.value.key2", "val3"));
`