Python MongoDB – create_index查询用法详细示例

2021年3月17日14:37:16 发表评论 1,167 次浏览

本文概述

MongoDB 是一个开源的面向文档的数据库。 MongoDB以键值对形式存储数据, 并且是NoSQL数据库程序。术语NoSQL表示非关系。

索引编制

索引有助于有效地查询文档。它存储一个特定字段或一组字段的值, 这些值由索引中指定的字段值排序。

PyMongo包含一个功能create_index()显式创建索引。默认_ID是文档中存在的唯一索引。此功能可以接受一个键或一个(键, 方向)对的列表。

语法如下:

create_index(keys, session=None, **kwargs)

让我们看一些例子。

范例1:

样本数据库:

Python MongoDB – create_index查询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)

输出如下:

Before Creating index
['_id_']

After Creating index
['_id_', 'student_id_1']
  1. 在这里, 我们创建一个名为学生卡使用create_index()方法。这导致文档中有两个索引_ID和学生卡.
  2. 使用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)

输出如下:

<module>中的DuplicateKeyError Traceback(最近一次通话最后一次)<ipython-input-62-264f0e13db93> 16 record = {'_id':4, 4, " student_id":873, " name":" John", " section":" A"} 17 —> 18 mycollection.insert_one(record)DuplicateKeyError:E11000重复键错误集合:GFG.College索引:student_id_1 dup键:{:873}

它引起了DuplicateKeyError因为已经有一个与student_id 873一起存在的文档, 并且我们正尝试插入另一个具有相同student_id的文档。发生此错误的原因是我们在字段Student_id上创建了索引并将其标记为唯一。

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: