MongoDB4 更新嵌套对象 item

时间:2021-02-03 17:32:20

标签: mongodb mongodb-query

我在更新 MongoDB 4 中的嵌套对象时遇到问题。

我写了一个操场,我正在做一些测试以解决问题..

我的愿望是:

  1. 我需要用小写字母覆盖“email”项目(获得的结果)。

  2. 我需要在“emailsS​​tatus”数组中包含的所有 N 个对象中,“emailAddress”项被自身覆盖,但为小写

我不能执行第二点,在操场上你会发现一切都准备好了,我正在执行的测试但我没有成功..我错了什么?

游乐场:https://mongoplayground.net/p/tJ25souNlYZ

1 个答案:

答案 0 :(得分:1)

  • 尝试$map迭代emailsStatus数组的循环并转换emailAddress小写,使用$mergeObjects将当前对象与更新电子邮件字段合并,
  • 查询部分的另一个建议是您可以使用 email is $type 来检查 string 的单个条件
db.collection.update(
  { email: { $type: "string } },
  [{
    $set: {
      email: { $toLower: "$email" },
      emailsStatus: {
        $map: {
          input: "$emailsStatus",
          in: {
            $mergeObjects: [
              "$$this",
              { emailAddress: { $toLower: "$$this.emailAddress" } }
            ]
          }
        }
      }
    }
  }],
  { multi: true }
)

Playground


使用emailAddress$cond检查$type数组中的空条件,

$map: {
  input: "$emailsStatus",
  in: {
    $mergeObjects: [
      "$$this",
      {
        emailAddress: {
          $cond: [
            { $eq: [{ $type: "$$this.emailAddress" }, "string"] },
            { $toLower: "$$this.emailAddress" },
            "$$this.emailAddress"
          ]
        }
      }
    ]
  }
}

Playground

相关问题