在文档中插入文档

发布于 2024-12-26 07:02:32 字数 834 浏览 4 评论 0原文

我使用 mongodb + java。我尝试将新文档插入到现有文档中。假设我有一个集合“Users”:

{"_id" :{"$oid" : "4dc9..."}, "name" :"Klaus", "gender" :"unknown", "adress" :"null"}

现在我想更新此文档,其中名称 == Klaus 并向键 adress 添加一个新文档(现在只有“null”)。所以我想要这样的东西:

{"_id" :{"$oid" : "4dc9..."}, "name" :"Klaus", "gender" :"unknown", "adress" :{"country" :"Austria", "city": "..."}}

How to do it in Java?我尝试过

//DBCollection col "Users"
String json = "{'country': '" + user.country + "', 'city': '" + user.city + "'}";
DBObject dbObject = (DBObject)JSON.parse(json);
col.update(new BasicDBObject().append("name", "Klaus"), dbObject); //not working

,没有收到任何错误消息,新文档不存在。我的json有问题吗?或者我是否需要另一个“更新”功能,也许是替换(将 adress:null 替换为 adress:new document)?感谢您的帮助!

Im using mongodb + java. I tried to insert a new document into an existing document. Lets say I have a collection "Users":

{"_id" :{"$oid" : "4dc9..."}, "name" :"Klaus", "gender" :"unknown", "adress" :"null"}

Now I would like to update this document where the name == Klaus and add a new document to the key adress (wheres now only "null"). So I would like to have something like this:

{"_id" :{"$oid" : "4dc9..."}, "name" :"Klaus", "gender" :"unknown", "adress" :{"country" :"Austria", "city": "..."}}

How to do it in Java? I tried

//DBCollection col "Users"
String json = "{'country': '" + user.country + "', 'city': '" + user.city + "'}";
DBObject dbObject = (DBObject)JSON.parse(json);
col.update(new BasicDBObject().append("name", "Klaus"), dbObject); //not working

I dont get any errormessage, the new document is just not there. Is something wrong with my json? Or do I need another "update" function, maybe a replace (replace adress:null with adress:new document)? Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栀梦 2025-01-02 07:02:32

看看你的更新。您甚至没有指定应该有一个“地址”字段。另请注意,您并不是在此处的文档中“插入”文档。相反,您将顶级文档的字段设置为嵌入文档的值。使用这个代替:

col.update(new BasicDBObject("name", "Klaus"), new BasicDBObject("$set", new BasicDBObject("address", dbObject)));

Look at your update. At no point do you even specify there should be a field "address". Also note that you're not "inserting" a document within a document here. Rather your setting a field of your top level document to a value that is an embedded document. Use this instead :

col.update(new BasicDBObject("name", "Klaus"), new BasicDBObject("$set", new BasicDBObject("address", dbObject)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文