gpt4 book ai didi

java - 如何更新mongo中的嵌入文档?

转载 作者:行者123 更新时间:2023-12-01 05:06:05 26 4
gpt4 key购买 nike

我在 mongo 数据库中有以下文档。

  { "_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"
}

我想要自动更新菜单 {
“名称”:“gdfgdfgdfg”,
“描述”:“dfgdgd”,
“文本”:“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"

}

但我想在同一个嵌入文档中进行更新。

任何人指导我......提前致谢

最佳答案

好吧,在读了几遍之后(英语......)我想我现在明白了。

您想要使用 _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);

希望这能解决问题。

关于java - 如何更新mongo中的嵌入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12641227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com