26

I seem to be struggling to find the right way of deleting a document. I.e. should I be using remove() or delete_one() for example and also what is the canonical method of deleting by id, which is a string.

I.e. should I be using the following:

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

or can I use another format?

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

What is the canonical form?

disruptive
  • 5,687
  • 15
  • 71
  • 135

2 Answers2

56

remove is deprecated in the 3.x release of pymongo, so the current canonical form would be to use delete_one:

from bson.objectid import ObjectId

result = mongo.db.xxx.delete_one({'_id': ObjectId(_id)})

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

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

You can simply do:

result = mongo.db.xxx.delete_one({})
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103