Python Mongodb Delete Data

Python Mongodb Python Mongodb

We can usedelete_one()method to delete a document. The first parameter of this method is the query object, which specifies which data to delete.

The test data used in this article is as follows (click the image to view it larger):

The following example deletes documents with the name field value "Taobao":

Example

#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["exampledb"] mycol = mydb["sites"] myquery = { "name": "Taobao" } mycol.delete_one(myquery) # Output after deletion for x in mycol.find(): print(x)

The output result is:

Delete Multiple Documents

We can usedelete_many()method to delete multiple documents. The first parameter of this method is the query object, which specifies 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["exampledb"] mycol = mydb["sites"] myquery = { "name": {"$regex": "^F"} } x = mycol.delete_many(myquery) print(x.deleted_count, "document(s) deleted")

The output result is:

1 个文档已删除

Delete All Documents in a Collection

delete_many() If an empty query object is passed to the method, it will delete all documents in the collection:

Example

#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["exampledb"] mycol = mydb["sites"] x = mycol.delete_many({}) print(x.deleted_count, "document(s) deleted")

The output result is:

5 个文档已删除

Delete a Collection

We can usedrop()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["exampledb"] mycol = mydb["sites"] mycol.drop()

If deletion succeeds, drop() returns true; if deletion fails (collection does not exist), it returns false.

We use the following command in the terminal to check whether the collection has been deleted:

> use exampledb
switched to db exampledb
> show tables;

Python Mongodb Python Mongodb

Other Extensions