単一ドキュメントの更新

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...