如何在 MongoDB 文件中替換子字串?
為了在 MongoDB 文件中替換子字串,你可以使用 replace() 函式。為了進一步理解,讓我們建立一個帶有文件的集合。建立帶有文件的集合的查詢如下 -
> db.replaceSubstringDemo.insertOne({"WebsiteURL":"www.gogle.com"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c76eaf21e9c5dd6f1f78276")
}在集合中顯示所有文件,使用 find() 方法。查詢如下 -
> db.replaceSubstringDemo.find().pretty();
輸出
{
"_id" : ObjectId("5c76eaf21e9c5dd6f1f78276"),
"WebsiteURL" : "www.gogle.com"
}這是在 MongoDB 文件中替換子字串的查詢 -
> db.replaceSubstringDemo.find({WebsiteURL:"www.gogle.com"}).forEach(function(url,k){
... url.WebsiteURL=url.WebsiteURL.replace("www.gogle.com","www.google.com");
... db.replaceSubstringDemo.save(url)
... });我們再次顯示集合中的文件,以驗證替換是否已完成。查詢如下 -
> db.replaceSubstringDemo.find().pretty();
輸出
{
"_id" : ObjectId("5c76eaf21e9c5dd6f1f78276"),
"WebsiteURL" : "www.google.com"
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP