更新嵌套文档并在mongodb中递增

时间:2015-09-03 05:14:43

标签: java mongodb mongodb-query

我想更新嵌套文档,如果存在,则使用新值增加旧值或插入新文档。

数据

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中,数组本质上是动态的。在上面的文档中,我需要更新~Waikato`的增量字段size值。而不是在区域数组中添加另一条记录。

我的代码

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 } ] }

请就这些问题向我提出建议。

1 个答案:

答案 0 :(得分:3)

您的positional $运算符只属于“更新部分,而不属于查询。此外,您需要在查询中.append(),否则您将覆盖:

BasicDBObject query = new BasicDBObject();
query.put("country", "New Zealand");
query.append("regions.region", "Waikato");

BasicDBObject update = new BasicDBObject()
    .append("$inc", new BasicDBObject().append("regions.$.size", 145));

collection.update(query, update, true, false);

基本上看起来像这样(明智的):

collection.update(
    { "country": "New Zealand", "regions.region": " "Waikato" },
    { "$inc": regions.$.size": 145 },
    true,
    false
)