MongoDB更新嵌套字段中的数据 [英] MongoDB update data in nested field

查看:191
本文介绍了MongoDB更新嵌套字段中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mongo作为我的数据库.我有数据:

i'm using Mongo to be my database. i have a data:

 {
   _id : '123'
   friends: [
     {name: 'allen', emails: [{email: '11111', using: 'true'}]}
   ]
 }

现在,我想装饰用户的电子邮件'_id为'123'的电子邮件 我这样写:

now, i wanna to motify user's friends' emails ' email, whose _id is '123' i write like this:

db.users.update ({_id: '123'}, {$set: {"friends.0.emails.$.email" : '2222'} })

这很容易,但是,当emails数组具有两个或更多数据时,这是错误的. 因此,我的问题是: 我如何在嵌套字段中对数据进行主题装饰---只有两个或多个嵌套数组?谢谢.

it's easy, but , it's wrong , when the emails array has two or more data. so, my question is: how can i motify the data in a nested filed --- just have two or more nested array? Thanks.

推荐答案

您需要使用点数组的符号.

也就是说,您应该将$替换为您要更新的元素的从零开始的索引.

That is, you should replace the $ with the zero-based index of the element you're trying to update.

例如:

db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} });

将更新第一个朋友的第一封电子邮件,并且

will update the first email of the first friend, and

db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.1.email" : '2222'} })

将更新第一个朋友的第二封电子邮件.

will update the second email of the first friend.

这篇关于MongoDB更新嵌套字段中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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