用于删除字段中部分文本的 MongoDB 更新语句 [英] MongoDB update statement to remove a portion of text in a field
问题描述
我有一个名为Url"的字段的 mongoDB 集合.这个集合中有很多记录.在此字段中,它始终包含以下文本:
I have a mongoDB collection with a field called "Url". There are many records in this collection. Inside this field, it always contains this text below:
"http://image-assets.s3.us-west-2.amazonaws.com/"例如 "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah.jpg"
我想删除http://image-assets.s3.us-west-2.amazonaws.com/",因此最终结果应该类似于folder1/folder2/blah.jpg"
I would like to remove the portion of "http://image-assets.s3.us-west-2.amazonaws.com/", so the final result should look like "folder1/folder2/blah.jpg"
想写一个mongodb的更新语句,不知道从何下手.我可以想到两件事:(a) 删除前 x 个字符,或 (b) 用空值替换文本.但是文本包含很多斜杠 (/)
I would like to write a mongodb update statement, I don't know where to start. I can think of two things: (a) remove the first x number of characters, or (b) replace the text with a null. However the text includes a lot of slashes (/)
感谢您的帮助.
推荐答案
这个带有更新结果的聚合查询将起作用:
This aggregation query with update on the result will work:
db.urls.aggregate( [
{
$project: {
url: {
$split: [
"$url",
"http://image-assets.s3.us-west-2.amazonaws.com/"
]
}
}
}
] ).forEach( doc => db.urls.updateOne( { _id: doc._id }, { $set: { url: doc.url[1] } } )
有了这两个输入文件:
{ url: "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah.jpg" }
{ url: "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah2.jpg" }
更新后的 url
字段会有值:
The updated url
field will have values:
folder1/folder2/blah.jpg
folder1/folder2/blah2.jpg
<小时>
使用要更新的 URL 字符串添加对 url
字段的检查.在上述聚合查询中的 $project
阶段之前添加这个 $match
阶段.
Adding a check for url
field with the URL string to be updated. Add this $match
stage before the $project
stage in the above aggregation query.
请注意,在正则表达式搜索字符串中^
表示以"开头,而.
(点)以\
为前缀(反斜杠),因此它仅被视为一个点(而不是正则表达式元字符).
Note that in the regex search string ^
means "starts with", and the .
(dot) is prefixed with a \
(backslash) so that it is considered as a dot only (not as regex meta-character).
{
$match: {
url: { $regex: '^http://image-assets\.s3\.us-west-2\.amazonaws\.com/' }
}
},
这篇关于用于删除字段中部分文本的 MongoDB 更新语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!