Actualizarea unui singur document

Introducere în MongoDB cu Python

Filip Schouwenaars

Machine Learning Researcher

De ce actualizăm sau înlocuim?

  • După adăugare, datele evoluează
    • Corectarea erorilor
    • Adăugarea informațiilor lipsă
    • Restructurarea documentelor
  • MongoDB oferă instrumente de actualizare și înlocuire
Introducere în MongoDB cu Python

Actualizarea unui singur 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
Introducere în MongoDB cu Python

Actualizarea mai multor documente

# 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
Introducere în MongoDB cu Python

Înlocuirea unui document complet

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,
  ...
}
Introducere în MongoDB cu Python

Să exersăm!

Introducere în MongoDB cu Python

Preparing Video For Download...