参考更新查询MongoDB中的现有字段

问题描述 投票:0回答:1

我正在尝试使用文档中的现有字段向 MongoDB 中的集合(该集合有大约 40k 文档)添加一个新字段,我正在运行以下更新查询

db.myCollection.updateMany( 
{ },
[
    { $set : { newField : "some_extra_string" + "$existingField1" + "other_extra_string" + "$existingField2" } }
])

但是 newField 正在更新为

"newField" : "some_extra_string$existingField1other_extra_string$existingField2"

它不是引用现有字段,而是附加字符串文字“$existingField1”/“$existingField2”。

我使用 MongoDB 文档作为我的来源:https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/#example-1--update-with-aggregation-pipeline -使用现有字段

在示例中,他们使用美元符号引用现有字段,我在这里做错了什么?

database mongodb mongodb-query nosql aggregation-framework
1个回答
0
投票

当前,您正在使用纯文本进行字符串连接。

相反,您需要

$concat
运算符将字符串与引用字段连接起来。

db.myCollection.updateMany({},
[
  {
    $set: {
      newField: {
        $concat: [
          "some_extra_string",
          "$existingField1",
          "other_extra_string",
          "$existingField2"
        ]
      }
    }
  }
])

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.