MongoDB PHP驱动程序-如何使用$replaceAll

91zkwejq  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(165)

如何用更新查询替换MongoDB中的部分字符串。
例如,我有这样的:

_id: 123
url:"test.com?from_user=1"
name:"Superhero"

_id:124
url:"regex.com?from_user=3"
name:"Journalist"

_id:123
url:"test.com?from_user=2"
name:"Software Developer"

我想用url =“www.example.com“的_id:123部分替换所有文档test.comsample.com,得到以下结果:

_id: 123
url:"sample.com?from_user=1"
name:"Superhero"

_id:124
url:"regex.com?from_user=3"
name:"Journalist"

_id:123
url:"sample.com?from_user=2"
name:"Software Developer"

我试过了

$collection->updateMany([
     '_id' => 123,
     'url' => [
          '$regex' => "test.com"
      ]
], [
     '$set' => [
          "url" => [
               '$replaceAll' => [
                    "input" => '$url',
                    "find" => "test.com",
                    "replacement" => "example.com"
                ]
           ]
     ]
], [
     'multi' => true
])

但此处显示错误:
'url.$replaceAll'中以美元($)为前缀的字段'$replaceAll'对于存储无效。

oug3syen

oug3syen1#

您的更新查询需要aggregation pipeline

db.collection.update({
  "_id": 123,
  "url": {
    "$regex": "test.com"
  }
},
[
  {
    "$set": {
      "url": {
        "$replaceAll": {
          "input": "$url",
          "find": "test.com",
          "replacement": "example.com"
        }
      }
    }
  }
],
{
  multi: true
})

Demo @ MongoDB Playground
如果您不是PHP开发人员,则需要将newObj参数作为数组传递:

$collection->updateMany([
     '_id' => 123,
     'url' => [
          '$regex' => "test.com"
      ]
], array([
     '$set' => [
          "url" => [
               '$replaceAll' => [
                    "input" => '$url',
                    "find" => "test.com",
                    "replacement" => "example.com"
                ]
           ]
     ]
]), [
     'multi' => true
])
  • 请注意:_id字段是MongoDB文档中的唯一标识符,不可能有重复_id的文档。*

相关问题