Python MongoDB Dokument löschen

Dokument löschen

Um ein Dokument zu löschen, verwenden wir delete_one() Method.

delete_one() Der erste Parameter der Methode ist das query-Objekt, das zur Definition des zu löschenden Dokuments verwendet wird.

Anmerkung:Falls die Suche mehrere Dokumente findet, wird nur das erste übereinstimmende Element gelöscht.

Example

Löschen des Dokuments mit der Adresse "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, which is 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