MongoEngine delete document

Question:

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.

Asked By: Jivan

||

Answers:

From what I understand and according to the note in the docs:

Note that this will only work if the document exists in the database and has a valid id

obj.delete() would only work if the object ID – the obj.id property – has a valid ObjectId value. In your case, you don’t have obj.id defined, use the objects.delete() syntax:

my_collection.MyCol.objects.delete()
Answered By: alecxe

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)
    ...
Answered By: Jace Browning

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()
Answered By: knittledan

You can delete one specific document using the following command

my_collection.MyCol.objects(id='some_id').delete()
Answered By: Anshuman

my_collection.MyCol.objects(id=’some_id’).delete()

Answered By: Kartikeya Mishra

In my case I forgot to mark the document id as the primary key.

from bson import ObjectId
from conn import db
class ProductModel(db.Document):
    meta = {'collection': 'products'}
    _id = db.ObjectIdField() #throws the exception
    _id = db.ObjectIdField(primary_key=True,default=ObjectId) #correct way to not throw exception

    @classmethod
    def getById(cls, idProduct: str):
        return cls.objects(_id=ObjectId(idProduto)).first()

How to use

#from bson import ObjectId

id = 630a18fb70392af65e9d63bc
if ObjectId.is_valid(id) == False:
    return {'message':'Provide a valid id.'}

ProductModel.getById(idProduct=id).delete()
Answered By: Bacar Pereira
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.