การรวม MongoDB operations

MongoDB เบื้องต้นใน Python

Filip Schouwenaars

Machine Learning Researcher

สร้าง Bulk Operation

from pymongo import InsertOne, UpdateOne    # import classes

operations = [ InsertOne({ # operation 1 "title": "Dune", "genre": ["action", "adventure", "drama"], "release_year": 2021, "rating": 8.0, "won_oscar": False }), UpdateOne( # operation 2 { "title": "Titanic" }, { "$set": { "won_oscar": True } } ) ]
result = mov.bulk_write(operations) # pass list to bulk_write
MongoDB เบื้องต้นใน Python

ทำความเข้าใจผลลัพธ์

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

ควรทราบไว้

  • ทำงานตามลำดับ: operation ก่อนหน้าจะไม่ถูก rollback
  • ต้องการความปลอดภัยมากขึ้น? ลองใช้ transactions
MongoDB เบื้องต้นใน Python

ทำไมต้องใช้ bulk_write?

  • มีประสิทธิภาพ
    • ส่ง operation ทั้งหมดใน request เดียว
    • ประหยัดเวลา ลด network overhead
  • ติดตามได้
    • result object เดียว
    • สรุปผลของทุก operation รวมกัน
    • ตรวจสอบและ debug ได้ง่ายขึ้น
  • เป็นระเบียบ
    • ไม่กระจาย operation ไปทั่ว
    • รวม logic ไว้ด้วยกัน อ่านง่ายขึ้น
MongoDB เบื้องต้นใน Python

รวม operation อะไรได้บ้าง?

  • ใช้ได้หลายรูปแบบ:

    • InsertOne()
    • UpdateOne() / UpdateMany() / ReplaceOne()
    • DeleteOne() / DeleteMany()
    • ReplaceOne()
  • เหมาะกับ:

    • การซิงค์ข้อมูล
    • การทำความสะอาดชุดข้อมูล
    • การนำเข้าข้อมูลจำนวนมาก
MongoDB เบื้องต้นใน Python

มาฝึกกันเถอะ!

MongoDB เบื้องต้นใน Python

Preparing Video For Download...