如何在MongoDB中更新字符串的子集? [英] How to update subset of a string in MongoDB?
本文介绍了如何在MongoDB中更新字符串的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更新monogdb中字符串的以下子集
I want to update the following subset of a string in monogdb
Collection: Paper
Field: URL
Document Current:
Name : House
URL : www.home.com/300x300
Document Updated
Name : House
URL : www.home.com/600x600
我已经尝试过了,但是似乎不起作用:
I have already tried this but it doesn't seem to be working:
db.Paper.find({Name:"House"}).forEach(function(e,i) {
e.URL=e.URL.replace("300","600");
db.Paper.save(e);
});
有什么想法吗?
推荐答案
您可以使用以下聚合之一来查询和更新:
You can use one of the following aggregations to query and update:
db.test.aggregate( [
{
$match: {
url: { $regex: "300x300" }
}
},
{
$addFields: {
url: { $split: [ "$url", "300" ] }
}
},
{
$addFields: {
url: {
$concat: [
{ $arrayElemAt: [ "$url", 0 ] },
"600",
{ $arrayElemAt: [ "$url", 1 ] },
"600",
{ $arrayElemAt: [ "$url", 2 ] }
]
}
}
}
] ).forEach( doc => db.test.updateOne( { _id: doc._id }, { $set: { url: doc.url } } ) )
With MongoDB version 4.2+ you can specify the aggregation instead of an update operation with updateMany:
db.test.updateMany(
{
url: { $regex: "300x300" }
},
[
{
$addFields: {
url: { $split: [ "$url", "300" ] }
}
},
{
$addFields: {
url: {
$concat: [
{ $arrayElemAt: [ "$url", 0 ] },
"600",
{ $arrayElemAt: [ "$url", 1 ] },
"600",
{ $arrayElemAt: [ "$url", 2 ] }
]
}
}
}
]
)
这篇关于如何在MongoDB中更新字符串的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文