在文档中插入文档
我使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看你的更新。您甚至没有指定应该有一个“地址”字段。另请注意,您并不是在此处的文档中“插入”文档。相反,您将顶级文档的字段设置为嵌入文档的值。使用这个代替:
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 :