Menggabungkan operasi MongoDB

Pengantar MongoDB di Python

Filip Schouwenaars

Machine Learning Researcher

Membangun Operasi Massal

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
Pengantar MongoDB di Python

Memahami hasil

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

Perhatikan

  • Dieksekusi berurutan: operasi awal tidak di-rollback
  • Ingin keamanan lebih ketat? Gunakan transaksi
Pengantar MongoDB di Python

Mengapa menggunakan bulk_write?

  • Efisien
    • Kirim semua operasi dalam satu permintaan
    • Hemat waktu, kurangi overhead jaringan
  • Terpantau
    • Satu objek hasil
    • Ringkasan terpadu untuk semua operasi
    • Lebih mudah diaudit dan di-debug
  • Rapi
    • Hindari operasi tersebar
    • Logika tetap terkelompok dan mudah dibaca
Pengantar MongoDB di Python

Apa yang bisa dikombinasikan?

  • Gunakan kombinasi apa pun dari:

    • InsertOne()
    • UpdateOne() / UpdateMany() / ReplaceOne()
    • DeleteOne() / DeleteMany()
    • ReplaceOne()
  • Cocok untuk:

    • Sinkronisasi data
    • Pembersihan dataset
    • Impor massal
Pengantar MongoDB di Python

Ayo berlatih!

Pengantar MongoDB di Python

Preparing Video For Download...