Jivan
Jivan

Reputation: 23098

MongoEngine delete document

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.

Upvotes: 6

Views: 7349

Answers (6)

Bacar Pereira
Bacar Pereira

Reputation: 1145

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()

Upvotes: 0

Kartikeya Mishra
Kartikeya Mishra

Reputation: 126

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

Upvotes: 0

Anshuman
Anshuman

Reputation: 31

You can delete one specific document using the following command

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

Upvotes: 2

knittledan
knittledan

Reputation: 764

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()

Upvotes: 6

Jace Browning
Jace Browning

Reputation: 12692

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)
    ...

Upvotes: 4

alecxe
alecxe

Reputation: 474241

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()

Upvotes: 2

Related Questions