📜  使用Python在 MongoDB 中进行索引

📅  最后修改于: 2022-05-13 01:54:38.241000             🧑  作者: Mango

使用Python在 MongoDB 中进行索引

通过在 MongoDB 集合中创建索引,查询性能得到了增强,因为它们以这样一种方式存储信息,使得遍历它变得更加容易和高效。由于 MongoDB 可以通过索引搜索查询,因此无需进行全面扫描。因此,它限制了需要检查查询条件的文档数量。

示例 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