Reputation: 148
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);
});
Any ideas?
Upvotes: 0
Views: 474
Reputation: 14287
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 ] }
]
}
}
}
]
)
Upvotes: 1
Reputation: 3812
Pretty simple, you have to use regex
instead of string
in the pattern of replace function as below:
> db.Paper.find({Name:"House"}).forEach(function (e, i) {e.URL = e.URL.replace(/300/g, "600"), printjson(e); db.Paper.save(e);} )
{
"_id" : ObjectId("5e016224a16075c5bd26fbe2"),
"Name" : "House",
"URL" : "www.home.com/600x600"
}
> db.Paper.find()
{ "_id" : ObjectId("5e016224a16075c5bd26fbe2"), "Name" : "House", "URL" : "www.home.com/600x600" }
>
So, there is a difference between e.URL.replace("300", "600")
and e.URL.replace(/300/g, "600")
. You should figureout it yourself.
For references, please go through this: https://flaviocopes.com/how-to-replace-all-occurrences-string-javascript/
Upvotes: 0