使用Python在 MongoDB 中进行索引
通过在 MongoDB 集合中创建索引,查询性能得到了增强,因为它们以这样一种方式存储信息,使得遍历它变得更加容易和高效。由于 MongoDB 可以通过索引搜索查询,因此无需进行全面扫描。因此,它限制了需要检查查询条件的文档数量。
Syntax– create_index([str1, direction], [str1, direction]……., optional)
Parameters are:
- str : string used for naming index, it can be one or more than one
- direction : can be one or many directions, it has to be one of these directions- descending, ascending, hashed, geosphere, geohaystack, geo2d or text
示例 1:
Python3
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Creating a single field index
res = doc.create_index("index_created")
print(res)
Python3
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Creating a single field index in descending order
res = doc.create_index([ ("index_descending", -1) ])
print(res)
Python3
from pymongo import MongoClient,, ASCENDING, DESCENDING
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Creating a compund field index in descending order
res = doc.create_index(
[
("ascending_index", 1),
("second_descnding_indexed", DESCENDING)
]
)
print(res)
输出:
index_created_1
示例 2:
Python3
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Creating a single field index in descending order
res = doc.create_index([ ("index_descending", -1) ])
print(res)
输出:
index_descending_-1
示例 3:
Python3
from pymongo import MongoClient,, ASCENDING, DESCENDING
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Creating a compund field index in descending order
res = doc.create_index(
[
("ascending_index", 1),
("second_descnding_indexed", DESCENDING)
]
)
print(res)
输出:
ascending_index_1
second_descnding_indexed_DESCENDING