更新單一文件

Python 中的 MongoDB 入門

Filip Schouwenaars

Machine Learning Researcher

為何要更新或取代?

  • 新增後,資料會演變
    • 修正錯誤
    • 補上遺漏資訊
    • 重構整份文件
  • MongoDB 提供工具可更新與取代
Python 中的 MongoDB 入門

更新單一文件

# 定義篩選條件以尋找要變更的文件
query_filter = { "title": "la la land" }

# 描述要變更的內容 update = { "$set": { "release_year": 2016 } }
# 執行更新 res = mov.update_one(query_filter, update)
res.modified_count
1
Python 中的 MongoDB 入門

更新多份文件

# 定義篩選條件(可能對應多份文件!)
query_filter = { "genre": "comedy" }

# 描述要變更的內容 update = { "$set": { "is_funny": True } }
# 套用至所有符合的文件 result = mov.update_many(query_filter, update)
print(result.modified_count)
9
Python 中的 MongoDB 入門

取代整份文件

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,
  ...
}
Python 中的 MongoDB 入門

一起來練習吧!

Python 中的 MongoDB 入門

Preparing Video For Download...