Delete a document in PyMongo with ID

I seem to be trying to find the right way to delete a document. That is, should I use remove () or delete_one (), as well as the canonical method of removing by id, which is string .

those. whether to use the following:

 mongo.db.xxx.delete_one({'_id': { "$oid" : str(_id) } }) 

or can i use a different format?

 mongo.db.xxx.remove({'_id': { "$oid" : str(_id) } }) mongo.db.xxx.remove({'_id': ObjectId(_id) }) 

What is the canonical form?

+6
source share
1 answer

remove deprecated in the release of pymongo 3.x, so delete_one will be used in the current canonical form:

 from bson.objectid import ObjectId result = mongo.db.xxx.delete_one({'_id': ObjectId(_id)}) 

The call returns DeleteResult , in which you can check the deleted_count field to see if it found a document to delete

+16
source

All Articles