Mongoengine 简明教程

MongoEngine - Advanced Queries

为了提高在文档中检索字段子集的效率,请使用 Objects 属性的 only() 方法。这将显著提高性能,特别是对于极大长度的字段,例如 ListField。将所需的字段传递给 only() 函数。如果在执行 only() 查询后访问了其他字段,则返回默认值。

In order to get more efficiency in retrieving a subset of fields in a document, use only() method of Objects attribute. This will significantly improve performance especially for fields with extremely large length such as ListField. Pass the required field to only() function. If other fields are accessed after executing only() query, default value is returned.

from mongoengine import *
con=connect('newdb')
class person (Document):
name=StringField(required=True)
city=StringField(default='Mumbai')
pin=IntField()
p1=person(name='Himanshu', city='Delhi', pin=110012).save()
doc=person.objects.only('name').first()
print ('name:',doc.name)
print ('city:', doc.city)
print ('PIN:', doc.pin)

Output

name: Himanshu
city: Mumbai
PIN: None

Note − 使用 city 属性的值作为默认值。由于未为 PIN 指定默认值,因此打印 None。

Note − The value of city attribute is used as default. As default is not specified for PIN, it prints None.

如果您需要丢失的字段,可以调用 reload() 函数。

You may call reload() function if you need missing fields.

当文档类具有 ListField 或 DictField 时,在对其进行迭代时,任何 DBREf 对象都会自动取消引用。为了进一步提高效率,特别是如果文档具有 ReferenceField,可以使用 select_related() 函数对查询数量进行限制,该函数会将 QuerySet 转换为列表并取消引用。

When a document class has a ListField or DictField, while iterating through it, any DBREf objects are automatically dereferenced. To increase the efficiency further, especially if the document has ReferenceField, number of queries can be limited by using select_related() function which converts QuerySet in a list and effects dereferencing.

MongoEngine API 包含 Q 类,该类可用于构建由多个约束条件组成的复杂查询。Q 表示查询的一部分,该部分可以通过关键字参数语法和二进制 & 和 | 运算符来初始化。

MongoEngine API contains Q class which is useful for constructing advanced queries consisting of number of constraints. Q represents a part of query which can be initialized by keyword argument syntax and binary & and | operators.

person.objects(Q(name__startswith=’H’) &Q(city=’Mumbai’))