Python MongoDB verwijderen document

Document verwijderen

Om een document te verwijderen, gebruiken we delete_one() Method.

delete_one() De eerste parameter van de methode is het query-object, gebruikt om het te definiëren document dat moet worden verwijderd.

Opmerking:Als de zoekopdracht meerdere documenten vindt, wordt alleen het eerste overeenkomende item verwijderd.

Example

Verwijder het document met het adres "Mountain 21":

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Mountain 21" }
mycol.delete_one(myquery)

Run Instance

Delete multiple documents

To delete multiple documents, use delete_many() Method.

delete_many() The first parameter of the method is a query object, used to define the documents to be deleted.

Example

Delete all documents with addresses starting 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.")

Run Instance

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.")

Run Instance