Combining MongoDB operations

Introduction to MongoDB in Python

Filip Schouwenaars

Machine Learning Researcher

Building a 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
Introduction to MongoDB in Python

Understanding the result

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

Keep in mind

  • Executed in order: earlier operations are not rolled back
  • Want stricter safety? Check out transactions
Introduction to MongoDB in Python

Why use bulk_write?

  • Efficient
    • Send all operations in a single request
    • Saves time, reduced network overhead
  • Trackable
    • Single result object
    • Unified summary of results of all operations
    • Easier to audit and debug
  • Clean
    • Avoids scattering operations
    • Keeps logic grouped and easier to read
Introduction to MongoDB in Python

What can you combine?

  • Use any mix of:

    • InsertOne()
    • UpdateOne() / UpdateMany() / ReplaceOne()
    • DeleteOne() / DeleteMany()
    • ReplaceOne()
  • Great for:

    • Syncing data
    • Cleaning up datasets
    • Bulk imports
Introduction to MongoDB in Python

Let's practice!

Introduction to MongoDB in Python

Preparing Video For Download...