Cập nhật một tài liệu

Nhập môn MongoDB với Python

Filip Schouwenaars

Machine Learning Researcher

Vì sao cập nhật hoặc thay thế?

  • Sau khi thêm, dữ liệu sẽ thay đổi
    • Sửa lỗi
    • Bổ sung thông tin thiếu
    • Tái cấu trúc toàn bộ tài liệu
  • MongoDB cung cấp công cụ để cập nhật và thay thế
Nhập môn MongoDB với Python

Cập nhật một tài liệu

# Xác định bộ lọc để tìm tài liệu cần đổi
query_filter = { "title": "la la land" }

# Mô tả thay đổi update = { "$set": { "release_year": 2016 } }
# Thực hiện cập nhật res = mov.update_one(query_filter, update)
res.modified_count
1
Nhập môn MongoDB với Python

Cập nhật nhiều tài liệu

# Định nghĩa bộ lọc (có thể khớp nhiều tài liệu!)
query_filter = { "genre": "comedy" }

# Mô tả thay đổi update = { "$set": { "is_funny": True } }
# Áp dụng cho mọi tài liệu khớp result = mov.update_many(query_filter, update)
print(result.modified_count)
9
Nhập môn MongoDB với Python

Thay thế toàn bộ tài liệu

query_filter = { "title": "the lion king" }

mov.find_one(query_filter)
{
   '_id': '68375bf5a63f71e478cdc7f5'
   'title': 'the lion king', 
   'release_year': 1994,
   ...
}
replacement = {
  "title": "the lion king",
  "genre": ["animation", "adventure", "drama"],
  "release_year": 2019,
  "rating": 6.8
}

mov.replace_one(query_filter, replacement)
mov.find_one(query_filter)
{
  '_id': '68375bf5a63f71e478cdc7f5',
  'title': 'the lion king'
  'release_year': 2019,
  ...
}
Nhập môn MongoDB với Python

Ayo berlatih!

Nhập môn MongoDB với Python

Preparing Video For Download...