如何在mongoengine中通过主键获取文档?

big*_*ind 2 python mongodb mongoengine

我正在将应用程序从 App Engine 的 ndb 移植到 mongoengine。ndb提供了该Model.get_by_id方法,我想用mongoengine来实现它。那么如何通过自动生成的 id 或设置为primary_keyTrue 的任何字段来获取文档呢?

big*_*ind 5

您可以使用with_id()

class MyDocument(Document):
    ...
    @classmethod
    def get_by_id(cls, id):
        return cls.objects.with_id(id)
Run Code Online (Sandbox Code Playgroud)

这将返回文档实例(如果存在)或None不存在。