OverStack
OverStack

Reputation: 767

Insert a document in a 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!

Upvotes: 0

Views: 379

Answers (1)

Remon van Vliet
Remon van Vliet

Reputation: 18595

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)));

Upvotes: 2

Related Questions