【问题标题】:Update a nested document filed and increment in mongodb在 mongodb 中更新嵌套文档并增加
【发布时间】: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


【解决方案1】:

您的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
)

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2014-09-23
    • 1970-01-01
    • 2021-02-13
    • 2013-03-19
    相关资源
    最近更新 更多