Basic Index

기본 구문

Create Index

  • createIndex{field: order}

    • Creates an index on this collection.

      db.my_collection.createIndex({address: 1})

Show Index

  • getIndexes()

    • Get information on collections’s indexes.

      db.my_collection.getIndexes()

Drop Index

  • dropIndex{field: order}

    • Drops the specified index on this collection.

    • To drop all indexes on this collection, use dropIndexes().

      db.my_collection.dropIndex({address:1})

Compound Index

  • Create indexes on more than one field.

  • db.my_collection.createIndex({name: -1, address: 1})

Indexing on Embedded Document

  • Embedded document와 Array에 인덱스를 사용하기 위해서는 아래와 같은 구문으로 사용하면 된다. 개념은 똑같기 때문에 이해하는 것에는 무리없을 것으로 보인다.

  • Indexes can be created on keys in embedded documents.

    db.collection.createIndex({'parent.child': 1})
  • To use the index to search for specific array elements efficiently.

    db.collection.createIndex({'items.name': -1})

Indexing Option

Unique Indexes

  • Unique indexes guarantee that each value will appear at most once in the index

    db.collection.createIndex({'key_1': 1}, {unique: true})

Sparse Indexes

  • Sparse indexes only contain entries for documents that have the indexed field skipping documents without it

    db.collection.createIndex({'key_2': 1}, {sparse: true})

Unique & Sparse

  • Unique indexes guarantee that each value will appear at most once in the index

    db.collection.createIndex({key_3: 1}, {unique: true, sparse: true})

Hint

  • To override MongoDB’s default index selection and query optimization process.

    db.collection.find().sort({'key_4': 1}).hint({'key_4': 1})

Last updated