在嵌套数组数场改变 [英] alter field by number in nested array

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

问题描述

假设有一个包含像

{ 
  name : 'ernie',
  likes : [
  {
    what : 'rubber duckie',
    howmuch : 5
  },
  {
    what : 'bert',
    howmuch : 3
  }]
}

{ 
  name : 'cookie monster',
  likes : [
  {
    what : 'cookies',
    howmuch : 100
  }]
}

如果在 0 厄尼元素的喜欢 -array应该有 howmuch - 值增加,比方说,1,有没有MongoDB的命令来做到这一点? JavaScript的当量是 ernie.likes [0] .howmuch ++

If the 0th element of ernie's likes-array should have its howmuch-value incremented, say, by 1, is there a MongoDB command to do this? The JavaScript-equivalent would be ernie.likes[0].howmuch++.

具体而言,您可以通过索引号访问数组中的元素

推荐答案

要通过的1递增 howmuch 字段值 0 日厄尼的喜好阵的元素,使用 $ INC 运营商,在点符号 按从零开始的索引位置来访问数组的元素:

To increment the howmuch field value by 1 of the 0th element of ernie's likes-array, use the $inc operator together with the dot notation to access the element of the array by the zero-based index position:

db.collection.update(
    {
        "name": "ernie"       
    }, 
    { 
        "$inc" : { "likes.0.howmuch" : 1 } 
    }
)

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

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