如何用更新查询替换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'对于存储无效。
1条答案
按热度按时间oug3syen1#
您的更新查询需要aggregation pipeline。
Demo @ MongoDB Playground
如果您不是PHP开发人员,则需要将newObj参数作为数组传递:
_id
字段是MongoDB文档中的唯一标识符,不可能有重复_id
的文档。*