文档菜单

文档首页开发应用程序Python 驱动程序PyMongo

使用索引优化查询

本页内容

  • 概述
  • 示例应用程序
  • 单字段索引
  • 复合索引
  • 多键索引
  • Atlas 搜索索引
  • 创建搜索索引
  • 列出搜索索引
  • 更新搜索索引
  • 删除搜索索引
  • 文本索引
  • 地理空间索引
  • 唯一索引
  • 通配符索引
  • 聚集索引
  • 移除索引

本页,您可以查看可复制的代码示例,展示如何使用 PyMongo 中的常见索引类型。

提示

要了解有关与索引一起工作的更多信息,请参阅与索引一起工作指南。要了解本页上显示的任何索引的更多信息,请参阅每个部分中提供的链接。

要使用本页上的示例,请将代码示例复制到示例应用程序或您自己的应用程序中。确保将代码示例中的所有占位符,例如<连接字符串 URI>,替换为您的 MongoDB 部署的相关值。

您可以使用以下示例应用程序测试本页上的代码示例。要使用示例应用程序,请执行以下步骤

  1. 确保已安装 PyMongo。

  2. 复制以下代码并将其粘贴到新的 .py 文件中。

  3. 从本页复制代码示例并将其粘贴到文件中指定的行。

1import pymongo
2from pymongo import MongoClient
3
4try:
5 uri = "<connection string URI>"
6 client = MongoClient(uri)
7
8 database = client["<database name>"]
9 collection = database["<collection name>"]
10
11 # start example code here
12
13 # end example code here
14
15 client.close()
16
17except Exception as e:
18 raise Exception(
19 "The following error occurred: ", e)
result = collection.create_index("<field name>")
print(f'Index created: {result}')

要了解有关单字段索引的更多信息,请参阅单字段索引指南。

result = collection.create_index([
("<field name one>", pymongo.ASCENDING),
("<field name two>", pymongo.ASCENDING)
])
print(f"Index created: {result}")

要了解有关复合索引的更多信息,请参阅复合索引指南。

result = collection.create_index("<array field name>")
print(f'Index created: {result}')

了解多键索引的更多信息,请参阅多键索引指南

了解有关Atlas搜索索引的更多信息,请参阅Atlas搜索索引指南

index = {
"definition": {
"mappings": {
"dynamic": True
}
},
"name": "<index name>",
}
collection.create_search_index(index)

了解有关创建搜索索引的更多信息,请参阅创建搜索索引指南

results = list(collection.list_search_indexes())
print('Existing search indexes:\n')
for index in results:
print(index)

了解有关列出搜索索引的更多信息,请参阅列出搜索索引指南

new_index = {
"definition": {
"mappings": {
"dynamic": True
}
},
"name": "<index name>",
}
collection.update_search_index("<name of index to update>", new_index)
print(f"Search index updated: {result}")

了解有关更新搜索索引的更多信息,请参阅更新搜索索引指南

collection.drop_index("<index name>")
print(f"Search index deleted: {result}")

了解有关删除搜索索引的更多信息,请参阅删除搜索索引指南

result = collection.create_index(
[( "<field name>", "text")],
default_language="english",
weights={ "<field name>": 10 }
)
print(f"Index created: {result}")

了解有关文本索引的更多信息,请参阅文本索引指南

result = collection.create_index([("<GeoJSON object field>", "2dsphere")])
print(f'Index created: {result}')

了解有关地理空间索引的更多信息,请参阅地理空间索引指南

result = collection.create_index("<field name>", unique=True)
print(f"Index created: {result}")

了解有关唯一索引的更多信息,请参阅唯一索引指南

result = collection.create_index({"$**": pymongo.ASCENDING})
print(f'Index created: {result}')

了解有关通配符索引的更多信息,请参阅通配符索引指南

collection = database.create_collection("<collection name>", clusteredIndex={
"key": {"_id": 1},
"unique": True
})

了解有关聚集索引的更多信息,请参阅聚集索引指南

collection.drop_index("<index_name>")

了解有关移除索引的更多信息,请参阅《使用索引指南》中的移除索引

← 从游标访问数据