【问题标题】:Mongodb: Update a field with data from a sub-sub field?Mongodb:使用子字段中的数据更新字段?
【发布时间】:2016-05-31 18:12:33
【问题描述】:

我正在尝试使用来自同一集合的数据更新集合中的字段,但来自其中的子子字段,并且要么无法正确获取语法,要么我做错了。

我已经花了很长时间在这里挖掘,但似乎无法到达任何地方。

这是 users 集合的示例结构:

{
  "_id": "12345qwerty",
  "services": {
    "oauth": {
      "CharacterID": 12345678,
      "CharacterName": "Official Username",
    },
  },
  "name": "what I want to change",
  "username": "OfficialUsername"
}

我正在尝试做的事情对于 SQL 来说非常简单,即:更新所有显示名称以匹配受信任的来源...

update users
set name = services.oauth.CharacterName;

...但是我在进入 MongoDB 时遇到了麻烦,而且我感觉我做错了。

这是我目前所拥有的,但它没有按预期工作。

db.users.find().snapshot().forEach(
  function (elem) {
    db.users.update(
      { _id: elem._id },
      { $set: { name: elem.services.oauth.CharacterName } }
    );
  }
);

我可以将名称设置为基本级别的任何名称,但不能将其设置为子级别的名称,因为它无法识别子字段。

任何帮助将不胜感激!

【问题讨论】:

  • 会不会因为某些用户没有必要的数据而失败,而 elem.services.oauth.CharacterName 您希望一切都到位?

标签: mongodb mongodb-query


【解决方案1】:
db.users.update({"services.oauth.CharacterName": {$exists: true}},{$set: {"name": "services.oauth.CharacterName"}},{multi:true})

我将您文档根目录的名称设置为等于子子文档中 services.oauth.CharacterName 中的值。 multi = true 将更新多个文档,我只更新具有 services.oauth.CharacterName 值的文档。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2020-06-10
    • 2013-11-05
    • 2011-04-27
    相关资源
    最近更新 更多