Reputation: 1812
I am trying to add new fields in existing Mongo document.
{
"_id" : ObjectId("51e390ade4b0a29154453698"),
"group_name" : "om",
"target_audience" : {
"gender" : "male",
"section" : "Item 4",
"catagory" : "Eletronics",
"location" : {
"country" : "Item 3",
"state" : "Item 3",
"city" : "Item 4"
}
}
}
This is my document .I want to add some more fields in this doc.I write following code.But instead of adding the records in same document it replaces previous one. My java code is :
BasicDBObject doc=new BasicDBObject();
BasicDBObject q=new BasicDBObject("group_name",selectedgn);
doc.put("date_from",frm);
doc.put("date_too",too);
doc.put("description",desc);
doc.put("url",url);
BasicDBObject doc1=new BasicDBObject();
doc1.put("Notification",doc);
con.coll.update(q,doc1);
Upvotes: 1
Views: 5068
Reputation: 361
Just a little update 6 years later:
Here is the working code for the current Mongo version:
Document filterDoc = new Document().append("tag", "existingTag");
Document updateDoc = new Document().append("$set", new Document().append("newField", "value"));
myCollection.updateMany(filterDoc, updateDoc);
Or use this to update just one:
myCollection.updateOne(filterDoc, updateDoc);
Upvotes: 0
Reputation: 2047
As others have said, use the $set operator. Your code should look like this (I only changed the last row):
BasicDBObject doc=new BasicDBObject();
BasicDBObject q=new BasicDBObject("group_name",selectedgn);
doc.put("date_from",frm);
doc.put("date_too",too);
doc.put("description",desc);
doc.put("url",url);
BasicDBObject doc1=new BasicDBObject();
doc1.put("Notification",doc);
con.coll.update(q,new BasicDBObject("$set",doc1));
Or, if you just want to update fields in the Notification sub-document:
BasicDBObject doc=new BasicDBObject();
BasicDBObject q=new BasicDBObject("group_name",selectedgn);
doc.put("Notification.date_from",frm);
doc.put("Notification.date_too",too);
doc.put("Notification.description",desc);
doc.put("Notification.url",url);
con.coll.update(q,new BasicDBObject("$set",doc));
Upvotes: 4
Reputation: 3157
There is extensive documentation here http://docs.mongodb.org/manual/core/update/#add-a-new-field-to-a-document This shouldn't replace the old properties.
Upvotes: 0