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

查看:38
本文介绍了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.

推荐答案

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

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

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天全站免登陆