我正在尝试在现有的Mongo文档中添加新字段。
{
"_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"
}
}
}
这是我的文档。我想在此doc中添加更多字段。我在下面的代码中编写。但不是在同一文档中添加记录,而是替换上一个。我的java代码是:
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);
答案 0 :(得分:4)
正如其他人所说,使用$ set运算符。您的代码应如下所示(我只更改了最后一行):
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));
或者,如果您只想更新通知子文档中的字段:
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));
答案 1 :(得分:0)
答案 2 :(得分:0)
六年后只需更新一下
以下是当前Mongo版本的工作代码:
Document filterDoc = new Document().append("tag", "existingTag");
Document updateDoc = new Document().append("$set", new Document().append("newField", "value"));
myCollection.updateMany(filterDoc, updateDoc);
或者使用它仅更新一个:
myCollection.updateOne(filterDoc, updateDoc);