Mongo-更新嵌套数组中的元素 [英] Mongo - Update elements in nested array
本文介绍了Mongo-更新嵌套数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文档,它看起来像
{
_id: "123xyz",
profile: {
emails: [
{
"address" : "foo@gmail.com",
"primary" : true
},
{
"address" : "bar@gmail.com",
"primary" : false
}
]
}
}
当用户将一个电子邮件地址设置为主要电子邮件地址时,如果他已经有其他电子邮件,我想将这些其他电子邮件设置为非主要电子邮件,即我想将所有不同于新主要电子邮件的电子邮件都设置为primary: false
。根据其他一些像this one这样的回答,这应该是可行的:
db.users.update(
{ _id: userId, 'profile.emails.address': { $ne: newEmailAddress } },
{ $set: { 'profile.emails.$.primary': false } }
);
但失败,The positional operator did not find the match needed from the query. Unexpanded update: profile.emails.$.primary
原始文档当前只有一封电子邮件与newEmailAddress
不同。
推荐答案
我在这里找到了您问题的答案: Update an item in an array that is in an array
在本例中使用该解决方案(使用您的结构):
db.mail.update({"profile.emails": {$elemMatch: {"address":
{$ne: "new@gmail.com" }}}}, {$set: {"profile.emails.$.primary": "false"}})
这篇关于Mongo-更新嵌套数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文