Python MongoDB Delete Data
We can use the delete_one() method to delete a document; the first parameter is a query object specifying which data to delete.
The test data used in this article is as follows (click the image to view full size):
The following example deletes the document whose name field value is "Taobao":
Example
#!/usr/bin/python3
import
pymongo
myclient
=
pymongo
.
MongoClient
(
"
mongodb://localhost:27017/
"
)
mydb
=
myclient
[
"
runoobdb
"
]
mycol
=
mydb
[
"
sites
"
]
myquery
= {
"
name
"
:
"
Taobao
"
}
mycol
.
delete_one
(
myquery
)
Output after deletion
for
x
in
mycol
.
find
(
)
:
(
x
)
The output is:

Delete multiple documents
We can use the delete_many() method to delete multiple documents; the first parameter is a query object specifying which data to delete.
Delete all documents whose name field starts with F:
Example
#!/usr/bin/python3
import
pymongo
myclient
=
pymongo
.
MongoClient
(
"
mongodb://localhost:27017/
"
)
mydb
=
myclient
[
"
runoobdb
"
]
mycol
=
mydb
[
"
sites
"
]
myquery
= {
"
name
"
: {
"
$regex
"
:
"
^F
"
} }
x
=
mycol
.
delete_many
(
myquery
)
(
x
.
deleted_count
,
"
documents deleted
"
)
The output is:
1 个文档已删除
Delete all documents in a collection
If delete_many() is passed an empty query object, it deletes all documents in the collection:
Example
#!/usr/bin/python3
import
pymongo
myclient
=
pymongo
.
MongoClient
(
"
mongodb://localhost:27017/
"
)
mydb
=
myclient
[
"
runoobdb
"
]
mycol
=
mydb
[
"
sites
"
]
x
=
mycol
.
delete_many
(
{}
)
(
x
.
deleted_count
,
"
documents deleted
"
)
The output is:
5 个文档已删除
Delete a collection
We can use the drop() method to delete a collection.
The following example deletes the customers collection:
Example
#!/usr/bin/python3
import
pymongo
myclient
=
pymongo
.
MongoClient
(
"
mongodb://localhost:27017/
"
)
mydb
=
myclient
[
"
runoobdb
"
]
mycol
=
mydb
[
"
sites
"
]
mycol
.
drop
(
)
If deletion succeeds, drop() returns true; if it fails (the collection does not exist), it returns false.
We use the following command in the terminal to check whether the collection has been deleted:
> use runoobdb
switched to db runoobdb
> show tables;
Python Mongodb