开始使用免费开始使用

使用 bulk_write()

正如您在视频中看到的,.bulk_write() 可以组合多种操作:

  • InsertOne()
  • UpdateOne() / UpdateMany() / ReplaceOne()
  • DeleteOne() / DeleteMany()
  • ReplaceOne()

您正在为电影数据库做一次春季清理,其中一些操作将非常有用!

首先,您的团队希望将所有高评分且获得奥斯卡奖的影片在首页标记为 "featured"。其次,为了减少冗余,您被要求移除所有很早以前上映的电影。

您将把这两项更改合并到一次 .bulk_write() 操作中,一并执行。

本练习是课程的一部分

Python 中的 MongoDB 入门

查看课程

练习说明

  • 完成 operations 中的第一个操作:更新所有评分大于等于 8.0 且获得过奥斯卡奖的电影;为这些电影设置新字段 "featured"True
  • 完成 operations 中的第二个操作:删除所有上映年份早于 1980 的电影。
  • mov 执行 .bulk_write() 操作,并将结果存为 res
  • 打印被修改的文档数量以及被删除的文档数量。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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.____)
编辑并运行代码