MongoDB-bewerkingen combineren

Introductie tot MongoDB in Python

Filip Schouwenaars

Machine Learning Researcher

Een bulkbewerking opzetten

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
Introductie tot MongoDB in Python

Het resultaat begrijpen

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

Onthoud

  • In volgorde uitgevoerd: eerdere acties worden niet teruggedraaid
  • Striktere veiligheid nodig? Kijk naar transacties
Introductie tot MongoDB in Python

Waarom bulk_write gebruiken?

  • Efficiënt
    • Stuur alles in één request
    • Bespaart tijd, minder netwerkoverhead
  • Te volgen
    • Eén resultaatobject
    • Geünificeerde samenvatting van alle resultaten
    • Makkelijker te controleren en debuggen
  • Overzichtelijk
    • Voorkomt versnipperde acties
    • Houdt logica gebundeld en leesbaar
Introductie tot MongoDB in Python

Wat kun je combineren?

  • Combineer vrijuit:

    • InsertOne()
    • UpdateOne() / UpdateMany() / ReplaceOne()
    • DeleteOne() / DeleteMany()
    • ReplaceOne()
  • Handig voor:

    • Data synchroniseren
    • Datasets opschonen
    • Bulkimporten
Introductie tot MongoDB in Python

Laten we oefenen!

Introductie tot MongoDB in Python

Preparing Video For Download...