小白教程
所有教程
关于
Search
172.69.58.33
172.69.58.33
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Python mongodb delete document”的源代码
本页内容
上一节:
Python_mongodb_sort
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:删除数据}}[[Category:python mongodb|5]] = Python Mongodb 删除数据 = [[python mongodb|Python Mongodb]] 我们可以使用 delete_one() 方法来删除一个文档,该方法第一个参数为查询对象,指定要删除哪些数据。 '''本文使用的测试数据如下(点击图片查看大图):''' [[64CCAEE8 05CB 4F14 8DB1 D9EB9B77FB17.png|64CCAEE8 05CB 4F14 8DB1 D9EB9B77FB17.png]] 以下实例删除 name 字段值为 "Taobao" 的文档: <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["xiaobaidb"] mycol = mydb["sites"] myquery = { "name": "Taobao" } mycol.delete_one(myquery) # 删除后输出 for x in mycol.find(): print(x) </sample> 输出结果为: === 删除多个文档 === 我们可以使用 delete_many() 方法来删除多个文档,该方法第一个参数为查询对象,指定要删除哪些数据。 删除所有 name 字段中以 F 开头的文档: <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["xiaobaidb"] mycol = mydb["sites"] myquery = { "name": {"$regex": "^F"} } x = mycol.delete_many(myquery) print(x.deleted_count, "个文档已删除") </sample> 输出结果为: <sample title="" desc="" lang="python" hererun="1"> 1 个文档已删除 </sample> === 删除集合中的所有文档 === delete_many() 方法如果传入的是一个空的查询对象,则会删除集合中的所有文档: <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["xiaobaidb"] mycol = mydb["sites"] x = mycol.delete_many({}) print(x.deleted_count, "个文档已删除") </sample> 输出结果为: <sample title="" desc="" lang="python" hererun="1"> 5 个文档已删除 </sample> == 删除集合 == 我们可以使用 drop() 方法来删除一个集合。 以下实例删除了 customers 集合: <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["xiaobaidb"] mycol = mydb["sites"] mycol.drop() </sample> 如果删除成功 drop() 返回 true,如果删除失败(集合不存在)则返回 false。 我们使用以下命令在终端查看集合是否已删除: <sample title="" desc="" lang="python" hererun="1"> > use xiaobaidb switched to db xiaobaidb > show tables; </sample> [[python mongodb|Python Mongodb]]
返回至“
Python mongodb delete document
”。
上一节:
Python_mongodb_sort