【问题标题】:MongoDB how to change field type in array from string to array and keep original valueMongoDB如何将数组中的字段类型从字符串更改为数组并保持原始值
【发布时间】:2022-01-07 14:08:37
【问题描述】:

原图 document

我有带有集合“测试”的数据库“测试”。在该集合中,我有一个名为“方法”的数组的文档,其中包含对象 0(可能还有更多对象 1、2、3、4 ...)。在这些对象中,我有带有工具“xray”的字符串字段“工具”。我希望该字符串字段“工具”成为工具数组。我找到了将工具字段更改为数组的命令:

db.testing.update(
  {},
  [{ $set: { "methods.tool": ["$methods.tool"] } }],
  { multi: true }
)

这可行,但它会创建一个额外的数组“0:Array”,我不想要那个

Outcome

我希望最终结果如下所示: end result

【问题讨论】:

  • 请注意,如果“methods”数组包含多个元素,则不会按您预期的方式工作。
  • 如果你下次可以用文本JSON提供数据,那就容易多了,不要为可以使用文本的东西发送图像,这样人们可以测试你的数据并给你一个查询.

标签: arrays mongodb mongo-shell


【解决方案1】:

查询

  • $map 更新方法的所有文档成员
  • $$this每次都是当前会员
  • $mergeObjects 用于添加更新的字段,由tool:xray 变为tool : [xray]

*该字段是数组一部分的路径,它们也是数组,“$methods.tool”是所有方法中所有工具的数组。

Test code here

update(
{},
[{"$set": 
    {"methods": 
      {"$map": 
        {"input": "$methods",
          "in": {"$mergeObjects": ["$$this", {"tool": ["$$this.tool"]}]}}}}}],
{"multi": true})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2021-02-27
    相关资源
    最近更新 更多