I have the following MongoEngine document
{
'_id': 'some_id',
'data': 'some_data'
}
How can I delete
this document using MongoEngine?
What I've tried:
import my_collection
obj = my_collection.MyCol.objects.get(_id='some_id')
# obj is correctly found - let's continue
obj.delete()
# mongoengine.errors.ValidationError: 'None' is not a valid ObjectId
obj.delete('some_id')
# TypeError: delete() takes 1 positional argument but 2 were given
obj.delete(_id='some_id')
# mongoengine.errors.ValidationError: 'None' is not a valid ObjectId
-- note
Oddly enough, the following works perfectly:
my_collection.MyCol.objects.delete()
# delete all documents in the collection
But I've followed MongoEngine docs, and still can't manage to delete just one specific document.
Deleting documents. To delete a document, call the delete() method. Note that this will only work if the document exists in the database and has a valid id .
To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.
remove() The remove() method removes documents from the database. It can remove one or all documents from the collection that matches the given query expression.
When referencing mongoengine ObjecIds you don't use the underscore.
obj = my_collection.MyCol.objects.get(id='some_id')
or
obj = my_collection.MyCol.objects(id='some_id')
obj.delete()
If your document overrides _id
, you must indicate that it's still the primary key. Change your document class definition from:
class MyCol(Document):
_id = db.StringField()
...
To specify the primary key:
class MyCol(Document):
_id = db.StringField(primary_key=True)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With