我在mongo db中有以下文档。
{ "_id" : ObjectId("50656f33a4e82d3f98291eff"),
"description" : "gdfgdfgdfg",
"menus" : [
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
},
{
"name" : "rtytry",
"description" : "gffhf",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98281f00")
}],
"select":"ffdfgd"
}
我想自动更新菜单
{
“name”:“gdfgdfgdfg”,
“description”:“dfgdgd”,
“text”:“dfgdfg”,
“关键”:“2”,
“onSelect”:“yyy”,
“_id”:ObjectId(“50656f3ca4e82d3f98291f00”)
}
我尝试使用以下代码:
BasicDBObject query = new BasicDBObject("_id", new ObjectId("50656f33a4e82d3f98291eff"));
BasicDBObject update = new BasicDBObject("_id", ObjectId("50656f3ca4e82d3f98291f00"));
BasicDBObject updateCommand = new BasicDBObject("$set", new BasicDBObject("menus", update));
collection.update(query, updateCommand);
我得到的结果是
{ "_id" : ObjectId("50656f33a4e82d3f98291eff"),
"description" : "gdfgdfgdfg",
"menus" :
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
},
"select":"ffdfgd"
}
但我想在同一个嵌入式文档中进行更新。
任何人都指导我......提前致谢
答案 0 :(得分:0)
好了几次读完之后(英语......)我想我现在明白了。
您希望使用带有_id 50656f3ca4e82d3f98291f00
的子文档:
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
}
您遇到的第一个问题是您的代码仅将menus
字段设置为此对象。你需要的是位置运算符。所以你需要做一个点符号查找(警告我的Java有点生锈):
query.append("menus._id", new ObjectId("50656f3ca4e82d3f98291f00"));
然后使用该位置运算符更新位置:
BasicDBObject update_document = new BasicDBObject("menus.$.name", my_new_subdocument.name);
update_document.append("menus.$.description", my_new_subdocument.description);
// All the other fields
BasicDBObject updateCommand = new BasicDBObject("$set", update_document);
希望这应该成功。