Updating a single document

Introduction to MongoDB in Python

Filip Schouwenaars

Machine Learning Researcher

Why update or replace?

  • After adding, data evolves
    • Correct mistakes
    • Add missing info
    • Restructure entire documents
  • MongoDB provides tools to update and replace
Introduction to MongoDB in Python

Updating a single document

# Define filter to find document to change
query_filter = { "title": "la la land" }

# Describe the change update = { "$set": { "release_year": 2016 } }
# Perform update res = mov.update_one(query_filter, update)
res.modified_count
1
Introduction to MongoDB in Python

Updating multiple documents

# Define filter (can match multiple documents!)
query_filter = { "genre": "comedy" }

# Describe the change update = { "$set": { "is_funny": True } }
# Apply change to all matching documents result = mov.update_many(query_filter, update)
print(result.modified_count)
9
Introduction to MongoDB in Python

Replacing a full document

query_filter = { "title": "the lion king" }

mov.find_one(query_filter)
{
   '_id': '68375bf5a63f71e478cdc7f5'
   'title': 'the lion king', 
   'release_year': 1994,
   ...
}
replacement = {
  "title": "the lion king",
  "genre": ["animation", "adventure", "drama"],
  "release_year": 2019,
  "rating": 6.8
}

mov.replace_one(query_filter, replacement)
mov.find_one(query_filter)
{
  '_id': '68375bf5a63f71e478cdc7f5',
  'title': 'the lion king'
  'release_year': 2019,
  ...
}
Introduction to MongoDB in Python

Let's practice!

Introduction to MongoDB in Python

Preparing Video For Download...