Using bulk_write()
As you saw in the video, you can use a handful of operations in .bulk_write():
InsertOne()UpdateOne()/UpdateMany()/ReplaceOne()DeleteOne()/DeleteMany()ReplaceOne()
You're doing some spring cleaning in your movie database where some of these will come in handy!
First, your team wants to flag all highly rated Oscar-winning films as "featured" on the homepage. Second, to reduce clutter, you're instructed to remove all movies released a long time ago.
You'll group both changes into a single .bulk_write() operation to execute them together.
Cet exercice fait partie du cours
Introduction to MongoDB in Python
Instructions
- Complete the first operation in
operationsto update all movies with a rating greater than or equal to8.0and that have won an oscar; set a new field"featured"toTruefor these movies. - Complete the second operation in
operationsto delete all movies with a release year before1980. - Perform the
.bulk_write()operation onmovand store the result asres. - Print out how many documents were modified and how many documents were deleted.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
from pymongo import UpdateMany, DeleteMany
operations = [
# Set featured to True for all movies with rating > 8 that won oscar
____(
{ "rating" : { ____: ____}, "won_oscar": ____ },
{ "$set": { ____: ____} }
),
# Remove all movies with release_year before 1980
____(
{ "release_year": { ____: ____} }
)
]
# Perform bulk write
res = mov.____
# Print out counts
print(res.____)
print(res.____)