MongoEngine删除文档

MongoEngine delete document

我有以下 MongoEngine 文档

{
    '_id': 'some_id',
    'data': 'some_data'
}

如何使用 MongoEngine delete 此文档?

我试过的:

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

--

奇怪的是,下面的代码完美运行:

my_collection.MyCol.objects.delete()
# delete all documents in the collection

但我已关注 MongoEngine 文档,但仍然无法删除 一个特定文档

据我了解并根据 note in the docs:

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

obj.delete() 仅在对象 ID - obj.id 属性 - 具有有效的 ObjectId 值时才有效。在您的情况下,您没有定义 obj.id,请使用 objects.delete() 语法:

my_collection.MyCol.objects.delete()

如果您的文档覆盖了 _id,您必须指明它仍然是主键。将您的文档 class 定义更改为:

class MyCol(Document):
    _id = db.StringField()
    ...

要指定主键:

class MyCol(Document):
    _id = db.StringField(primary_key=True)
    ...

在引用 mongoengine ObjecIds 时不要使用下划线。

obj = my_collection.MyCol.objects.get(id='some_id')

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

您可以使用以下命令删除一个特定文档

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

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