我有一个关键的11-07-2018,下面有3个值(“ testing”:2,“ analysis”:8,“ dev”:4),如下所示。
"Name":"Samaja"
"Dates":[{
11-07-2018: {
"testing" : 2,
"analysis" : 8,
"dev" : 4
}
}]
我要基于密钥更新文档(2018年11月7日),并删除现有值(“测试”:2,“分析”:8,“开发”:4)并插入新值(“ code”:9,“ tt”:6)基于相同的键(11-07-2018)。
答案 0 :(得分:1)
db.test.update(
{ "Name":"Samaja", //to filter documents. Anything can be used.
"Dates.11-07-2018":{$exists:true} //mandatory, otherwise update will throw an error
},
{$set:
{"Dates.$.11-07-2018":{"code":9,"tt":6}}
},
{multi:false //can be set to true if multiple document need to be updated
}
)
编辑 如果要向现有文档中添加字段,则代码略有不同:
BasicDBObject searchQuery = new BasicDBObject().append("Name", "Samaja").append("Dates.11-07-2018", new BasicDBObject().append("$exists", true));
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("Dates.$.11-07-2018.code", 9).append("Dates.$.11-07-2018.cc", 2));
collection.updateOne(searchQuery, updateQuery);
答案 1 :(得分:0)
无法在Java中进行测试,但这应该是这样的方式:
BasicDBObject searchQuery = new BasicDBObject().append("Name", "Samaja").append("Dates.11-07-2018",new BasicDBObject().append("$exists",true));
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("Dates.$.11-07-2018", new BasicDBObject().append("code",9).append("tt":6)));
collection.update(searchQuery, updateQuery);