Python MongoDB Delete Document
- Previous Page MongoDB Sort
- Next Page MongoDB Delete Collection
Delete document
To delete a document, we use delete_one()
Method.
delete_one()
The first parameter of the method is the query object, which is used to define the document to be deleted.
Note:If the query finds multiple documents, only the first matching item will be deleted.
Example
Delete the document with the address "Mountain 21":
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": "Mountain 21" } mycol.delete_one(myquery)
Delete multiple documents
To delete multiple documents, use delete_many()
Method.
delete_many()
The first parameter of the method is a query object, which is used to define the documents to be deleted.
Example
Delete all documents whose address starts with the letter S:
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": {"$regex": "^S"} } x = mycol.delete_many(myquery) print(x.deleted_count, " documents deleted.")
Delete all documents in the collection
To delete all documents in the collection, pass an empty query object to delete_many()
Method:
Example
Delete all documents from the "customers" collection:
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] x = mycol.delete_many({}) print(x.deleted_count, " documents deleted.")
- Previous Page MongoDB Sort
- Next Page MongoDB Delete Collection