Mongoengine 简明教程
MongoEngine - Indexes
索引的集合导致更快的查询处理。默认情况下,每个集合都自动在 _id
字段上建立索引。此外,您可以在一个或多个字段上创建索引。
An indexed collection results in faster processing of queries. By default, every collection is automatically indexed on _id field. In addition, you can create index on one or more fields.
使用 Compass,我们可以非常轻松地构建索引。单击下图所示的 Indexes 选项卡上的 CREATE INDEX 按钮:
Using Compass, we can build index very easily. Click on CREATE INDEX button on Indexes tab as shown in figure below−

将出现一个如所示的对话框。选择索引的名称、要建立索引的字段、索引的顺序(升序或降序)和其他选项。
A dialog box appears as shown. Choose name of index, field on which to index, order of index (ascending or descending) and other options.

在使用 MongoEngine 时,索引是通过指定 Document 类定义的元数据中的“indexes”键创建的。
While using MongoEngine, indexes are created by specifying ‘indexes’ key in meta dictionary of definition of Document class.
indexes 属性的值是字段列表。在以下示例中,我们要求 student 集合中的文档按 name 字段建立索引。
Value of indexes property is a list of fields. In the following example, we ask documents in student collection be indexed according to name field.
from mongoengine import *
con=connect('mydata')
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':['name']}
s1=student()
s1.name='Avinash'
s1.course='DataScience'
s1.save()
s2=student()
s2.name='Anita'
s2.course='WebDesign'
s2.save()
默认情况下,索引顺序为升序。可以通过对升序添加“+”,对降序添加“-”来指定顺序。
By default, indexing order is ascending. Order may be specified by prepending ‘+’ for ascending or ‘-‘ for descending order.
要创建复合索引,请使用字段名称的元组,可以选择附加 + 或 - 符号来指示排序顺序。
To create compound index, use a tuple of field names, optionally having + or – symbol attached to indicate sort order.
在以下示例中,student 文档类包含对名称和课程的复合索引的定义(注意 - 以课程字段为前缀的符号,表示索引按名称升序和课程降序构建。
In the following example, student document class contains definition of compound index on name and course (note - symbol prefixed to course field which means index is built namewise ascending and coursewise descending order.
from mongoengine import *
con=connect('mydata')
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[('name','-course')]}
s1=student()
s1.name='Avinash'
s1.course='DataScience'
s1.save()
s2=student()
s2.name='Anita'
s2.course='WebDesign'
s2.save()
MongoDB Compass 将如下所示显示索引 -
MongoDB Compass will show indexes as below −

“索引”的值可能是各种选项的字典,如下所示:
Value of ‘indexes’ may be a dictionary of various options as below −
fields |
The fields to index. |
cls |
If allow_inheritance is turned on, you can configure whether the index should have the _cls field added automatically. |
sparse |
Whether the index should be sparse. |
unique |
Whether the index should be unique. |
expireAfterSeconds |
automatically expire data from a collection by setting the time in seconds |
name |
Allows you to specify a name for the index |
collation |
Allows to create case insensitive indexes |
以下示例在 name 字段上创建索引,该索引在 3600 秒后过期。
Following example creates index on name field that expires after 3600 seconds.
from mongoengine import *
con=connect('mydata')
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[{
'fields': ['name'],
'expireAfterSeconds': 3600
}
]
}
要指定文本索引,请使用“$”符号作为字段名称前缀,对于哈希索引,请使用“#”作前缀。
To specify text index, prefix field name with ‘$’ sign and for hashed index, use ‘#’ as prefix.
如此指定的索引在向集合中添加文档时会自动创建。要禁用自动创建,请在元属性中将 “ auto_create_index ” 设置为 False。
Indexes so specified are created automatically as documents are added in the collection. To disable automatic creation, set ‘auto_create_index’ to False in meta attribute.
我们有带有 Document 类的方法 list_indexes() ,它显示可用索引的列表。
We have list_indexes() method with Document class that displays list of available indexes.
print (student.list_indexes())
[[('name', 1)], [('_id', 1)]]
要在元字典中不存在的字段上创建索引,请使用 create_index() 方法。以下代码将在 course 字段上创建索引 -
To create index on a field not in the meta dictionary, use create_index() method. The following code will create index on course field −
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[{
'fields': ['name'],
'expireAfterSeconds': 3600
}
]}
student.create_index(['course'])