mongodb:如何通过索引号更新数组元素 [英] mongodb: how to update array element by index number

查看:89
本文介绍了mongodb:如何通过索引号更新数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有这样的文档:

{
    _id: 'sdsdfsd',
    a: [
          { x: 0, y: 0, z: 0 }
          { x: 0, y: 0, z: 0 }
          { x: 0, y: 0, z: 0 }
          { x: 0, y: 0, z: 0 }
    ]
}

因此,如果您有_id和一个索引号(例如:2).现在,对于该索引,我想将x值更改为1.在mongo中可能吗?还是应该首先检索整个数组,更新特定值并通过将其插入回去来更新整个数组?

So, if you have the _id and an index number (say: 2). Now, for that index I want to change the x value to 1. Is this possible in mongo or should I first retrieve the whole array, update the specific value and update the whole array by inserting it back ?

推荐答案

您可以使用点符号从update中的基于0的索引访问update中的特定数组元素:

You can access a specific array element in an update by its 0-based index using dot-notation:

// Set the x property of the third element of a to 1
db.test.update({_id: 'sdsdfsd'}, {$set: {'a.2.x': 1}})

这篇关于mongodb:如何通过索引号更新数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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