Оновлення одного документа

Вступ до MongoDB у Python

Filip Schouwenaars

Machine Learning Researcher

Навіщо оновлювати або замінювати?

  • Після додавання дані змінюються
    • Виправляйте помилки
    • Додавайте відсутні відомості
    • Переструктуровуйте цілі документи
  • MongoDB має інструменти для оновлення та заміни
Вступ до MongoDB у Python

Оновлення одного документа

# 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
Вступ до MongoDB у Python

Оновлення кількох документів

# 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
Вступ до MongoDB у Python

Заміна всього документа

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,
  ...
}
Вступ до MongoDB у Python

Давайте потренуємось!

Вступ до MongoDB у Python

Preparing Video For Download...