更新嵌套文档并在mongodb中增加 [英] Update a nested document filed and increment in mongodb

查看:239
本文介绍了更新嵌套文档并在mongodb中增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to update a nested document filed if present increment an old value with new value or insert a new document.

New Zealand,Waikato,Hamilton,1004
New Zealand,Waikato,Auckland,145
New Zealand,Otago,Dunedin,1068



Json



Json

{ "_id" : ObjectId("55e7d2a72f68907c17cfcb2f"), "country" : "New Zealand", 
"regions" : [ { "region" : "Waikato", "size" : 1004 }, 
{ "region" : "Waikato", "size" : 145 }, { "region" : "Otago", "size" : 1068 } ] }

在文档 regions 数组中本质上是动态的。在上面的文档中,我需要更新~Waikato`的增量字段 size 的值。而不是在区域数组中放入另一条记录。

In document regions array is dynamic in nature. In above document I need to update an increment field size value of ~Waikato`. Instead of putting an another record in array of regions.

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);



我需要这样的输出:



I need output like these:

{ "_id" : ObjectId("55e7d2a72f68907c17cfcb2f"), "country" : "New Zealand", "regions" : [ { "region" : "Waikato", "size" : 1149 }, { "region" : "Otago", "size" : 1068 } ] }

请建议我在这些问题上。

Please suggest me on these issue.

推荐答案

你的位置 $ 运算符只属于更新部分而不是查询。还需要<$在查询中c $ c> .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);

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

Basically looks like this ( shell wise ) :

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

这篇关于更新嵌套文档并在mongodb中增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆