【问题标题】:How to update a double nested value inside an array of multiple documents?如何更新多个文档数组中的双嵌套值?
【发布时间】:2018-12-10 19:53:56
【问题描述】:

想象以下城市记录集合:

{
  "city": "London",
  "inhabitants": [
    {
      "id": "34543534",
      "user": {
        "name": "Jonathan Deer",
        "email": "john@btinternet.com"
      }
    },
    {
      "id": "0454534",
      "user": {
        "name": "Tanya Patel",
        "email": "tanya@btinternet.com"
      }
    },
    {
      "id": "4345345",
      "user": {
        "name": "Catherine King",
        "email": "catherine@gmail.com"
      }
    }
  ]
}
{
  "city": "Manchester",
  "inhabitants": [
    {
      "id": "980003",
      "user": {
        "name": "Benjamin Thaw",
        "email": "benny@btinternet.com"
      }
    },
    {
      "id": "734488",
      "user": {
        "name": "Craig Longstone",
        "email": "craig@gmail.com"
      }
    },
    {
      "id": "4400093",
      "user": {
        "name": "Arnold Greentree",
        "email": "arnold@btinternet.com"
      }
    },
  ]
},

我要做的是遍历每个城市的每个 inhabitants 数组,看看那里的人是否有一个包含 btinternet.com 的电子邮件地址在里面。对于那些我想发送一个新标志 isBT: true 的用户和其他所有人(例如 gmail.com 用户)isBT: false:

"user": {
  "name": "Tanya Patel",
  "email": "tanya@btinternet.com"
  "isBT" true
}

我尝试了以下查询 - 第一个查询将所有查询设置为 isBT: false 而第二个查询在电子邮件地址中搜索“btinternet.com”并设置 isBT: true强>:

db.city.update({ "inhabitants.user.email": {$exists: true}}, {$set: { "inhabitants.$.user.isBT": false}}, {multi: true})

db.city.update({ "inhabitants.user.email": {$regex: "btinternet.com"}}, {$set: { "inhabitants.$.user.isBT": true}}, {multi: true})

问题是,当我执行第二个查询时,有几个居民记录留下了 isBT: false,即使它们包含必要的“btinternet.com”电子邮件地址。似乎只有第一个符合条件的用户记录才会更新...有没有办法更新所有“inhabitants”数组的所有用户记录? p>

我查看了使用位置运算符 $[],但我们的数据库是在 2.6.3 版本上,但这个运算符仅在 3.6 中引入...

【问题讨论】:

    标签: arrays mongodb


    【解决方案1】:

    简短的回答是“不”。

    长答案是“不,因为您的 MongoDB 版本不支持这样的操作”。您需要...
    1. 检索所有匹配的文档并通过数据的服务器端处理执行完整的数组更新(例如使用 MongoDB cursor.forEach()),
    2. 将你的匹配扩展到"inhabitants.user.isBT": true(使用 $elemMatch) 并重复执行更新查询,直到 修改文档的数量为 0(即没有更多的数组 要更新的元素),或
    3.更新你的MongoDB版本和任何 依赖于当前版本功能的服务器端代码 在2.63.6 之间发生了变化。

    此问题的任何解决方案都需要比单个查询更多的努力。没有办法绕过它。这是一颗难以下咽的药丸,但确实没有好的替代品。

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2015-07-13
      • 1970-01-01
      • 2012-05-18
      • 2022-01-02
      • 2013-09-03
      • 1970-01-01
      • 2017-04-28
      • 2016-10-06
      相关资源
      最近更新 更多