Categories
MongoDB

Thay thế SubString trong MongoDB Document

Trong quá trình làm việc với MongoDB, có thể chúng ta cần thay thế một giá trị của một field, bạn có thể sử dụng cú pháp dưới đây để thực hiện việc đó.

db.myCollection.updateMany(
  { fieldName: { $regex: /old/ } },
  [{
    $set: { fieldName: {
      $replaceOne: { input: "$fieldName", find: "old", replacement: "new" }
    }}
  }]
)
  1. { fieldName: { $regex: /old/ } } => MongoDB sẽ tìm vào document có fieldName là /old/ và trả lại kết quả.

2. Tiếp theo, nó sẽ thay thế old với field.

Ví dụ: Replace String in MongoDB

Tạo một collection như sau:

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

Chạy command line:

db.teams.updateMany(
  { conference: { $regex: /Western/ } },
  [{
    $set: { conference: {
      $replaceOne: { input: "$conference", find: "Western", replacement: "West" }
    }}
  }]
)

Kết quả thu được:

{ _id: ObjectId("620139494cb04b772fd7a8fa"),
  team: 'Mavs',
  conference: 'West',
  points: 31 }
{ _id: ObjectId("620139494cb04b772fd7a8fb"),
  team: 'Spurs',
  conference: 'West',
  points: 22 }
...

Bạn có thể thực hiện tương tự với nested object.

db.teams.insertOne({team: "Mavs", conference: "Western", points: 31, profile: {src: "https://olddomain.com"}})
db.teams.updateMany(
  { profile.src: { $regex: /https:\/\/olddomain\.com/ } },
  [{
    $set: { profile.src: {
      $replaceOne: { input: "$profile.src", find: "olddomain.com", replacement: "newdomain.com" }
    }}
  }]
)

Leave a comment