是否可以在没有 strict=False 的情况下使用 MongoEngine 删除字段?

Is it possible to delete a field with MongoEngine, without strict=False?

我在 MongoDB 中有很多数据,我们主要通过 MongoEngine 访问这些数据,有时数据首先出现在字段 F1 中,后来我们决定字段 F2 是一个更好的地方它,所以我们把它移到那里,并停止使用 F1。

这很方便,但现在我们在旧的 F1 键中得到了一堆陈旧(或无用)的数据,并且无缘无故地使用空的 F1 键创建了新文档。

虽然 MongoDB 无模式很方便,但我仍然欣赏 strict=True 功能(默认情况下打开),除非绝对必要,否则尽量避免关闭它。我不喜欢关闭 所有 集合的安全检查。

那么有没有什么方法可以从我的 MongoDB 集合中删除字段 F1,而无需停机且无需 strict=False

MongoEngine 有什么办法可以说 "This is an old field. You can load it (or ignore it) if it's there, but don't create it for any new documents" 吗?

If I remove the field from my database first, MongoEngine will create it for any new records, until the model is updated

仅当您明确写入该字段或该字段设置了默认值时才为真。否则该字段将不存在于 MongoDB 中。

因此,作为第一步,我建议删除写入该字段的代码并删除默认值(或将其设置为 None)。然后从数据库中删除该字段是安全的。

下面一个小证明:

import mongoengine

class Foo(mongoengine.Document):
    a = mongoengine.IntField()
    b = mongoengine.ListField(default=None)

f = Foo().save()
type(f.a)  # NoneType
type(f.b)  # NoneType

以及数据库查询:

> db.foo.findOne()
{ "_id" : ObjectId("56c49ae8ee8b341b4ea02fcb") }