Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 898
Jivan Avatar asked May 26 '16 16:05

Jivan


People also ask

How do I delete MongoEngine?

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 .

How do I remove all files from a collection in MongoDB?

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.

Which command will remove all documents in a collection with field age set to 10?

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.


2 Answers

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()
like image 73
knittledan Avatar answered Oct 01 '22 04:10

knittledan


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)
    ...
like image 24
Jace Browning Avatar answered Oct 01 '22 04:10

Jace Browning