Mongodb 嵌套数组内的增量值 [英] Mongodb Increment value inside nested array

查看:31
本文介绍了Mongodb 嵌套数组内的增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Spring 中使用 mongotemplate,我想知道如何以原子方式增加我在数组中的一个文档的值.假设我们有

I´m using mongotemplate for Spring, and I was wondering how I could increment a value of one of my documents that I have in an array atomically. Imagine that we have

{'a':1,
   b:[{_id:341432,
       c:2
      },
      {_id:341445,
       c:3
      }]};

我想要的是将 _id 341445 的 c 从 3 增加到 4

What I would like is increment c from 3 to 4 for the _id 341445

我一直在使用 findAndModify,但我不知道如何为数组中的嵌套文档制作它.

I have been using findAndModify but I dont know how can I make it for a nested document in an array.

问候.

推荐答案

要更新数组字段中的元素,可以使用 位置$运算符

To update an element in an array field, you can use the positional $ operator

例如下面的js将_id 341445的c从3增加到4:

For example, the following js increments c from 3 to 4 for _id 341445:

db.collection.update({a:1, "b._id":341445} , {$inc:{"b.$.c":1}})

这篇关于Mongodb 嵌套数组内的增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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