Javascript 如何在MongoDB中更新字符串的子集?
我想更新monogdb中字符串的以下子集Javascript 如何在MongoDB中更新字符串的子集?,javascript,mongodb,mongodb-query,mongodb-update,Javascript,Mongodb,Mongodb Query,Mongodb Update,我想更新monogdb中字符串的以下子集 Collection: Paper Field: URL Document Current: Name : House URL : www.home.com/300x300 Document Updated Name : House URL : www.home.com/600x600 我已经试过了,但似乎不起作用: db.Paper.find({Name:"House"}).forEach(function(e,i) {
Collection: Paper
Field: URL
Document Current:
Name : House
URL : www.home.com/300x300
Document Updated
Name : House
URL : www.home.com/600x600
我已经试过了,但似乎不起作用:
db.Paper.find({Name:"House"}).forEach(function(e,i) {
e.URL=e.URL.replace("300","600");
db.Paper.save(e);
});
有什么想法吗?非常简单,在替换函数的模式中,您必须使用
regex
而不是string
,如下所示:
> 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" }
>
因此,在e.URL.replace(“300”,“600”)
和e.URL.replace(/300/g,“600”)
之间存在差异。你应该自己弄清楚
有关参考信息,请浏览以下内容:您可以使用以下聚合之一进行查询和更新:
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 } } ) )
使用MongoDB 4.2+版,您可以通过以下方式指定聚合而不是更新操作:
另外,如果您想替换所有部分,我很确定您必须执行
e.URL.replace(/300/g,'600')
yes sorry'db.Paper.save(e);'我现在试试第二个建议。谢天谢地@taplar你是有错误还是什么都没发生?这回答了你的问题吗?
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 ] }
]
}
}
}
]
)