【发布时间】:2015-09-03 05:14:42
【问题描述】:
我想更新一个嵌套文档(如果存在的话)用新值增加一个旧值或插入一个新文档。
数据
New Zealand,Waikato,Hamilton,1004
New Zealand,Waikato,Auckland,145
New Zealand,Otago,Dunedin,1068
Json
{ "_id" : ObjectId("55e7d2a72f68907c17cfcb2f"), "country" : "New Zealand",
"regions" : [ { "region" : "Waikato", "size" : 1004 },
{ "region" : "Waikato", "size" : 145 }, { "region" : "Otago", "size" : 1068 } ] }
在文档regions 中,数组本质上是动态的。在上面的文档中,我需要更新一个增量字段size ~Waikato` 的值。而不是在区域数组中放置另一条记录。
我的代码
BasicDBObject query = new BasicDBObject();
query.put("country", "New Zealand");
query.put("regions.$.region", "Waikato");
BasicDBObject data = new BasicDBObject().append("$inc", new BasicDBObject().append("regions.$.size", 145));
BasicDBObject command = new BasicDBObject();
command.put("$set", data);
collection.update(query, command, true, false);
我需要这样的输出:
{ "_id" : ObjectId("55e7d2a72f68907c17cfcb2f"), "country" : "New Zealand", "regions" : [ { "region" : "Waikato", "size" : 1149 }, { "region" : "Otago", "size" : 1068 } ] }
请就这些问题向我提出建议。
【问题讨论】:
标签: java mongodb mongodb-query