Python MongoDB – create_index 查询
MongoDB 是一个开源的面向文档的数据库。 MongoDB以键值对的形式存储数据,是一个NoSQL数据库程序。 NoSQL 一词的意思是非关系型的。
索引
索引有助于有效地查询文档。它存储特定字段或一组字段的值,这些字段按索引中指定的字段值排序。
PyMongo 包含一个函数create_index()来显式创建索引。默认情况下, _id是文档中存在的唯一索引。此函数可以接受一个键或(键,方向)对的列表。
句法:
create_index(keys, session=None, **kwargs)
让我们看一些例子。
示例 1:
样本数据库:
Python3
from pymongo import MongoClient
# creation of MongoClient
client = MongoClient()
# Connect with the portnumber and host
client = MongoClient("mongodb://localhost:27017/")
# Access database
mydatabase = client['GFG']
# Access collection of the database
mycollection = mydatabase['College']
# Before Creating index
index_list = sorted(list(mycollection.index_information()))
print("Before Creating index")
print(index_list)
# Creating index
mycollection.create_index("student_id", unique = True)
# After Creating index
index_list = sorted(list(mycollection.index_information()))
print("\nAfter Creating index")
print(index_list)
Python3
from pymongo import MongoClient
# creation of MongoClient
client = MongoClient()
# Connect with the portnumber and host
client = MongoClient("mongodb://localhost:27017/")
# Access database
mydatabase = client['GFG']
# Access collection of the database
mycollection = mydatabase['College']
record = {'_id': 4,
"student_id": 873,
"name": "John",
"section": "A"}
mycollection.insert_one(record)
输出:
Before Creating index
['_id_']
After Creating index
['_id_', 'student_id_1']
- 在这里,我们使用 create_index() 方法创建一个名为student_id的索引。这导致文档_id和student_id中有两个索引。
- 使用index_information()方法,我们得到集合中的所有索引,
示例 2:
Python3
from pymongo import MongoClient
# creation of MongoClient
client = MongoClient()
# Connect with the portnumber and host
client = MongoClient("mongodb://localhost:27017/")
# Access database
mydatabase = client['GFG']
# Access collection of the database
mycollection = mydatabase['College']
record = {'_id': 4,
"student_id": 873,
"name": "John",
"section": "A"}
mycollection.insert_one(record)
输出:
DuplicateKeyError Traceback (most recent call last)
16 record = {‘_id’: 4, “student_id”: 873, “name”: “John”, “section”: “A”}
17
—> 18 mycollection.insert_one(record)
DuplicateKeyError: E11000 duplicate key error collection: GFG.College index: student_id_1 dup key: { : 873 }
它会引发DuplicateKeyError ,因为已经存在一个文档,其 student_id 为 873,并且我们正在尝试插入另一个具有相同 student_id 的文档。发生此错误是因为我们在字段 student_id 上创建了一个索引并将其标记为唯一。