【问题标题】:Mongo - Update elements in nested array [duplicate]Mongo - 更新嵌套数组中的元素
【发布时间】:2017-01-05 21:40:52
【问题描述】:

我有一个看起来像这样的文档

{
  _id: "123xyz",
  profile: {
    emails: [
      {
        "address" : "foo@gmail.com",
        "primary" : true
      },
      {
        "address" : "bar@gmail.com",
        "primary" : false
      }
    ]
  }
}

当用户将电子邮件地址设置为主要电子邮件地址时,如果他已经有其他电子邮件,我想将这些其他电子邮件设置为非主要电子邮件,即我想给与新主要电子邮件不同的所有电子邮件标记@ 987654323@。根据 this one 等其他一些 SO 答案,这应该可行:

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不同的电子邮件。

【问题讨论】:

  • 请详细说明你想要什么?
  • 好吧,我希望与newEmailAddress 不同的电子邮件能够获得primary: false 的标志,并且查询运行不会失败

标签: mongodb updates


【解决方案1】:

在这里我找到了您问题的答案: 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"}})

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2020-03-16
    • 2022-01-22
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多