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"
}