组合 MongoDB 操作

Python 中的 MongoDB 入门

Filip Schouwenaars

Machine Learning Researcher

构建批量操作

from pymongo import InsertOne, UpdateOne    # 导入类

operations = [ InsertOne({ # 操作 1 "title": "Dune", "genre": ["action", "adventure", "drama"], "release_year": 2021, "rating": 8.0, "won_oscar": False }), UpdateOne( # 操作 2 { "title": "Titanic" }, { "$set": { "won_oscar": True } } ) ]
result = mov.bulk_write(operations) # 将列表传给 bulk_write
Python 中的 MongoDB 入门

理解结果

print(result.inserted_count)
1
print(result.modified_count)
1

请注意

  • 顺序执行:较早的操作不会回滚
  • 需要更高安全性?请查看事务
Python 中的 MongoDB 入门

为何使用 bulk_write?

  • 高效
    • 一次请求发送所有操作
    • 省时,减少网络开销
  • 可追踪
    • 单一结果对象
    • 汇总所有操作结果
    • 更易审计与调试
  • 简洁
    • 避免操作分散
    • 逻辑成组,更易阅读
Python 中的 MongoDB 入门

可以组合什么?

  • 可任意混用:

    • InsertOne()
    • UpdateOne() / UpdateMany() / ReplaceOne()
    • DeleteOne() / DeleteMany()
    • ReplaceOne()
  • 适用于:

    • 数据同步
    • 数据清理
    • 批量导入
Python 中的 MongoDB 入门

让我们来练习!

Python 中的 MongoDB 入门

Preparing Video For Download...