Mongodb で文字列を置換する方法 (例あり)
次の構文を使用して、MongoDB のフィールド内の特定の文字列を置き換えることができます。
db.myCollection.updateMany(
{ fieldName: { $regex : /old/ } },
[{
$set : { fieldName: {
$replaceOne : { input: " $fieldName ", find: " old ", replacement: " new " }
}}
}]
)
この特定の例では、 myCollectionという名前のコレクション内の「fieldName」という名前のフィールド内の文字列「old」を「new」に置き換えます。
次の例は、次のドキュメントを使用して収集チームで実際にこの構文を使用する方法を示しています。
db.teams.insertOne({team: " Mavs ", conference: " Western ", points: 31})
db.teams.insertOne({team: " Spurs ", conference: " Western ", points: 22})
db.teams.insertOne({team: " Rockets ", conference: " Western ", points: 19})
db.teams.insertOne({team: " Celtics ", conference: " Eastern ", points: 26})
db.teams.insertOne({team: " Cavs ", conference: " Eastern ", points: 33})
db.teams.insertOne({team: " Nets ", conference: " Eastern ", points: 38})
例: MongoDB の文字列を置換する
次のコードを使用して、会議フィールドの文字列「Western」を「West」に置き換えます。
db.teams.updateMany(
{ conference: { $regex : /Western/ } },
[{
$set : { conference: {
$replaceOne : { input: " $conference ", find: " Western ", replacement: " West " }
}}
}]
)
更新されたコレクションは次のようになります。
{ _id: ObjectId("620139494cb04b772fd7a8fa"),
team: ' Mavs ',
conference: ' West ',
points: 31 }
{ _id: ObjectId("620139494cb04b772fd7a8fb"),
team: ' Spurs ',
conference: ' West ',
points: 22 }
{ _id: ObjectId("620139494cb04b772fd7a8fc"),
team: ' Rockets ',
conference: ' West ',
points: 19 }
{ _id: ObjectId("620139494cb04b772fd7a8fd"),
team: ' Celtics ',
conference: ' Eastern ',
points: 26 }
{ _id: ObjectId("620139494cb04b772fd7a8fe"),
team: ' Cavs ',
conference: ' Eastern ',
points: 33 }
{ _id: ObjectId("620139494cb04b772fd7a8ff"),
team: ' Nets ',
conference: ' Eastern ',
points: 38 }
会議フィールドに文字列「Western」が含まれていたすべての文書の会議フィールドには「West」が含まれることに注意してください。
会議フィールドに文字列「Western」が含まれていない文書は、単に元の文字列を保持します。
注: $replaceOne関数の完全なドキュメントはここで見つけることができます。
追加リソース
次のチュートリアルでは、MongoDB で他の一般的な操作を実行する方法について説明します。
MongoDB: フィールドに文字列が含まれているかどうかを確認する方法
MongoDB: 新しいフィールドを追加する方法
MongoDB: フィールドを削除する方法