인덱스 (Index)
Functions for Index
Creates an index on this collection.
create_index([(‘index_name’, order)])
e.g.) my_collection.create_index([(‘address’, 1)])
Get information on collections’s indexes
index_information()
e.g.) my_collection.index_information()
Drops the specified index on this collection
drop_index ([(‘index_name’, order)])
my_collection.drop_index([(‘address’, 1)])
To drop all indexes on this collection, use drop_indexes()
Compound Index
Create indexes on more than one field.
my_collection.create_index([
(‘name’, pymongo.DESCENDING),
(‘address’, pymongo.ASCENDING)])
e.g.)
my_collection.create_index([(‘name’, -1), (‘address’, 1)])
Indexing on Embedded Document
Indexes can be created on keys in embedded documents.
collection.create_index([('parent.child', pymongo.ASCENDING)])
Indexing to Array
collection.create_index([('items.name', pymongo.DESCENDING)])
Unique & Sparse Index
Unique indexes guarantee that each value will appear at most once in the index
collection.create_index([('key_1', 1)], unique=True)
Sparse indexes only contain entries for documents that have the indexed field skipping documents without it.
collection.create_index([('key_2', 1)], sparse=True)
Unique & Sparse
collection.create_index([(key_3', 1)], unique=True, sparse=True)
Hint
To override MongoDB’s default index selection and query optimization process.
collection.find().sort([('key_4', 1)]).hint([('key_4', 1)])
Geospatial Index
Type
pymongo.GEO2D ==> 2d
pymongo.GEOSPHERE ==> 2dsphere
collection.create_index( [ (‘field’, TYPE) ] ) # Create Inde
collection.drop_index( [ (‘field’, TYPE) ] ) # Drop Index
Example
from pymongo import MongoClient, GEOSPHERE
client = MongoClient()
db = client.geo
col = db.states
col.create_index([("loc", GEOSPHERE)])
Text Index
Create a text index on one field
collection.create_index(
[ ( 'field', pymongo.TEXT ) ] )
Create text indexes on multiple fields
collection.create_index(
[ ( 'field_1', pymongo.TEXT ),
( 'field_2', pymongo.TEXT ) ] )
Specify the weight of an indexed
collection.create_index(
[ ( 'field_1', pymongo.TEXT ),
( 'field_2', pymongo.TEXT ) ],
weights={ 'field_1' : 3, 'field_2' : 2 } )
Last updated
Was this helpful?