0% found this document useful (0 votes)
30 views29 pages

MongoDB Indexes

This guide provides an overview of MongoDB indexes, explaining their importance in optimizing query performance and detailing how to create, manage, and drop indexes using various methods. It covers single field and compound indexes, their creation, and the use of methods like createIndex(), dropIndex(), and getIndexes() to manipulate them. Additionally, it emphasizes the significance of index selection for application performance and the internal workings of MongoDB's indexing system.

Uploaded by

sainianshul0712
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
30 views29 pages

MongoDB Indexes

This guide provides an overview of MongoDB indexes, explaining their importance in optimizing query performance and detailing how to create, manage, and drop indexes using various methods. It covers single field and compound indexes, their creation, and the use of methods like createIndex(), dropIndex(), and getIndexes() to manipulate them. Additionally, it emphasizes the significance of index selection for application performance and the internal workings of MongoDB's indexing system.

Uploaded by

sainianshul0712
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 29
‘An Essential Guide to MongoD8 Indexes: MongoDB Indexes This section introduces you to MongoDB indexes that help perform queries faster and more efficiently. After completing the tutorials in this section, you'll — ee have a good understanding of indexes and how to use them more effectively. You'll understand the following key topics: What indexes are and why you need to use them. ¢ How to select fields to index. _~ * Understand various types of indexes in MongoDB. * How to evaluate the index usage. — How to manage indexes such as creating and removing them. Indexes are an important part of your application. And you'll see that selecting the right indexes for your collections is crucial to performance. © Create indexes (https://www. mongodbtutorial.org/mongodb-indexes/mongodb- createindex/) — introduce you to the index concept and show you how to use the createlndex() method to create an index for a field of a collection. Drop indexes (nttps://www.mongodbtutorial.org/mongodb-indexes/mongodb-drop- . dex/) - learn how to drop an index from a collection. index/) — Ce ound indexes (https://www mongodbtutorial.org/mongodb-indexes/mongodb- * Comp! d-index/) ~ learn the compound indexes that contain references to compound: multiple fields of a collection. i 1” viet oanimanenattindnyes! bine thinaw monn b os ‘grorga, 10:50 AM ‘An Essential Guide to MangoDB Indexes « Unique indexes (https://www.mongodbtutorial ora/mongodb-indexes/mongodb-uniques index/) — show you how to use unique indexes to enforce the uniqueness of values in a field across documents of a collection. OAM featons. 105 Mongo08 createIndex() \ _) mongoDB 7 TUTORIAL ’ MongoDB createlndex + Summary: in this tutorial, you'll learn how to use MongoDB createIndex() ‘method to create an index for a field in a collection to speed up queries. A quick introduction to indexes Suppose you have a book that contains a list of movies: To find a movie with the title pirates of Silicon Valley , you need to scan every page of the book until you find the match. This is not efficient. If the book has an index that maps titles with page numbers, you can look up the movie title in the index to find the page number: anand reimanaranininvecmonnedtctatindes 23, 10:50AM anor MongoD8 ereatelndex() Pimpernel’ Smith 1 Pirates of Silicon Valley 201 Twas the Night 300 In this example, the movie with the title Pirates of Silicon valley is located on page 201 . Therefore, you can open page 201 to get detailed information about the movie: x | jPimpernet’ Smith 3 | p the i Open the page 201. | 4 titlein | Pirates of Silicon Valley 201 In this analogy, the index speeds up the search and makes it more efficient. The MongoDB index works in a similar way. To speed up a query, you can create an index for a field of a collection. However, when you insert, update, or delete the documents from the p Ve — collection, MongoDB needs to update the index accordingly. In other words, an index improves the speed of document retrieval at the cost of additional write and storage space to maintain the index data structure. Internally, MongoDB uses the B-tree structure to store the index. ly, Load sample data simuacimanandh-erastaindox! I cr nenimanandi-ine . ‘1073. 1050M MongoD8 createlndex( We'll use the movies collection from the mflix sample database to demonstrate how the indexes work in MongoDB. First, download the movies.json file and place it in a folder on your computer e.g. c:\data\movies. json Second, import the movies.json file into the mflix database using the mongoimport (https://mww.mongodbtutorial .org/mongodb-tools/mongoimport/) tool: mongoimport c:\data\movies.json -d mflix -c movies List indexes of a collection By default, all collections have an index on the _id field. To list the indexes of a collection, you use the getIndexes() method with the following syntax: — oo NE db.collection.getIndexes() 4 In this syntax, the collection is the name.of the collection that you want to get the indexes. For example, collection in the mflix database: the following shows the indexes of the movies db. sales.getIndexes() Output: [{vi 2 key: { id: 1 }, name: ‘_id ' } J ramanantindavesimnnanaerestainen! ine tnawas mennstsnsedal Py Si a sotto 0123, 10:50 AM ‘snoves, ‘Mongo08 erentalndex() The output shows the index name the key : { _id : ‘_id_! and index key _id . The value 1 in 1} indicates the ascending order of the _id values in the index. When an index contains one field, it's called a single field index. However, if an index holds references to multiple fields, it is called a compound index. This tutorial focuses on a single field index. Explain a query plan The following query finds the movie with the title Pirates of Silicon Valley db.movies .find({ title: 'Pirates of Silicon Valley }) To find the movie, MongoDB has to scanthe movies collection to find the match. Before executing a query, the MongoDB query optimizer comes up with one or more query execution plans and selects the most efficient one. To get the information and execution statistics of query plans, you can use the explain() method: db.collection. explain() For example, the following returns the query plans and execution statistics for the query that finds the movies with the title Pirates of Silicon Valley : | amnimannednindavscimnnandh-erestsinjov! a patna rhaune monacha Te “410/23, 10:50 AM MongoD8 createlndex() db.movies.find({ title: ‘Pirates of Silicon Valley* })-explain('executionstats') The explain() method returns a lot of information. And you should pay attention to the following winningplan winningPlan: { stage: 'COLLSCAN', filter: { title: { '$eq': ‘Pirates of Silicon Valley’ } direction: ‘forward’ } ———— The winningPlan returns the information on the plan that the query optimizer came up with. In this example, the query planner comes up with the COLLSCAN that stands for the collection scan. pili ek hacia detect Also, the executionStats shows that the result contains one document and the execution time is 9 milliseconds: we executionStats: { éxecutionSuccess: true, nReturned: 1, executionTimeMillis: 9, pnteviat ernimanandisindayaslmanonthereatindnd huine tims mana gr 110728. 10:50AM ‘MongoD8 createindex() totalKeysExamined: 0, totalDocsExamined: 23539, Create an index for a field in a collection To create an index for the title field, you use the createIndex() method as follows: db .movies.createIndex({title:1}) _ Output: title In this example, we pass 4 document to the createIndex() method. The { title: 1} document contains the field and value pair where: The field is the index key ( year )- The value describes the type of index for the year field. The value 1 for descending index and -1 for ascending index. The createIndex() method returns the index name. In this example, it returns the title_1 which is the concatenation of the field and value. The following query shows the indexes of the movies collection: db movies -getindexes() anthsindevestmananndtncreateinas! ‘310128, 1050AM Output: {vi 2, key: { id: 1}, name: ‘id ' }, {vi 2, key: { title: 1}, name: ‘title 1‘ } The output shows two indexes, one is the default index and another is the year_1 index that we have created. | By default, MongoDB names an index by concatenating the indexed keys.and each key's direction in the index (i.e. 1 or -1) using underscores as a separator. For example, an index created on { title: 1} hasthename title. The following returns the query plans and execution statistics for the query that finds the movie with the title Pirates of Silicon Valley : db.movies.find({ title: ‘Pirates of Silicon Valley’ }) This time the query optimizer uses the index scan ( IXSCAN ) instead of the collection scan ( COLLSCAN ): winningPlan: { 3110728, 10:80AM MongoDB createlndex() stage: ‘FETCH’, inputStage: { stage: ‘IXSCAN', keyPattern: { title: 1 }, indexName: ‘title_1', isMultikey: false, multikeyPaths: { title: [] }, isUnique: false, isSparse: false, isPartial: false, indexVersion: 2, direction: ‘forward’, indexBounds: { title: [ ‘["Pirates of Silicon Valley", "Pirates of Silicor ] } t 3 Also, the execution time ( executiontimemillis ) was down to almost zero from 2 milliseconds: ote executionstats: { executionsuccess : true, nreturned: 1, J os Aenmndinn Maerandina Oedat 310123, 10:50 AN Morg208 createrdex() executionTimeMillis: 0, totalkeysExamined: 1, totalDocsExamined: 1, Summary * Anindex improves the speed of document retrieval at the cost of additional write and storage space to maintain its data structure. « Use the createIndex() method to create an index for a field ina collection. * Use the getIndexes() method to list the indexes of a collection. ¢ Use the explain() method to get the information and execution statistics of query plans. nonandt-indevaclmananah-reateindev! nnndihinitesial nnimannnst eas MongoD8 Drop index mongoDB TUTORIAL MongoDB Drop Index Summary: in this tutorial, you'll learn how to use the MongoDB dropIndex() method to drop an index from a collection. Introduction to the MongoDB drop index To drop an index from a collection, you use the db. collection. dropindex() method: db.collection.dropIndex(index) In this syntax, the index specifies an index to be dropped. The index can be either a.string that specifies the name of an index or a document that describes the specification of the index that you want to drop. Note that you cannot drop the default index onthe _id field. ay Starting in MongoDB 4.2, you cannot use the db. collection. dropIndex('*') to drop all non-_id indexes. Instead, you use the dropIndexes() method: db. collection .dropIndexes() tne uaa manana cen . ‘3710/28. 10:51 AM Annandine Macennding Dados = MongoD Brop Index MongoDB drop index examples Let's take some examples of dropping one or more indexes from a collection. 1) Drop an index example First, create a new index (https://www.mongodbtutorial.org/mongodb-indexes/mongodb- createindex/) for the year field in the movies collection: db.movies.createIndex({year: 1}) Output: year_1 In this example, the createIndex() method creates an index with the name year_l. Second, show all the indexes of the movies collection by using the getIndexes() method: db.movies.getIndexes() Output: { vi 2, key: { id: 1}, mame: '_id_' }, pnimennedindnvesimnnnndhironnday! bine tiwwew manana yt0123, 10:51AM Monqo08 Drop Indox { vi 2, key: { year: 1}, name: ‘year 1° } Third, drop the year_1 index using the dropindex() method: db.movies .dropIndex('year_1') Output: { nIndexesWas: 2, ok: 1 } The output shows that one index has been dropped. Finally, verify the index deletion using the getIndexes() method: db.movies.getIndexes() Output: [ {vi 2. key: { _id: 1 }, name: ‘aid }] | The output shows that the year_1 index was deleted and is dex | list of the movies collection. . | | 2) Drop an index by the index speci” | First, create an index for runtime field neater Tes eS 6L m——— yi0723, 1051 AM 9 MongoD8 Drop Index db.movies.createIndex({runtime: -1}) second, list the indexes of the movies collection: db.movies.getIndexes() Output: { vi 2, key: { id: 1}, name: '_id_’ in {vi 2, key: { runtime: -1 }, name: *puntime_-1" } Third, drop the index . runtime_-1 but use the index specification instead of the index name: db.movies. dropIndex ({runtime: -1})5 Output: { nIndexesWas: 2, ok: 1 } 3) Drop all non-_id indexes example First, create two indexes for the year and runtime fields of the movies collection: am «he crnmeuur ennnnnannniar cergennini 310123, 10:51 AM 'Mongo08 Drop Index db movies. createIndex({year: 1}) db.movies.createIndex({runtime: 1}) Second, show the indexes of the movies collection: db.movies.getIndexes() Output: {vi 2, key: { _id: 1 }, name: ‘Lid’ }, { vi 2, key: { year: 1 }, name: ‘year_1' }, { vi 2, key: { runtime: 1 }, name: ‘puntime_1' } Third, drop all non-_id indexes of movies collection using the dropIndexes() method: db.movies.dropIndexes() Output: { nIndexesWas: 3, *non-_id indexes dropped for collection’, msg: attuineevesimannaddennindax! 30123, 10:51 ANt Mongo0B Orop Index ok: 1 Summary e Use the dropIndex() to drop an index specified by name or specification from a collection. * The default index for the _id field cannot be dropped. © Use the dropIndexes() to drop all non-_id indexes of a collection. vine has mannaditerat enimnanndvindawasimannndth trend ne a 310128, 1082 MongoD8 Compound tn \ mongoDB PTUTORIAL MongoDB Compound index Summary: in this tutorial, you'll learn about MongoDB compound indexes and how to create a compound index for fields in a collection. Introduction to the MongoDB compound indexes A compound index is an index that holds a reference to multiple fields of a collection. In general, a compound index can speed up the queries that match on multiple fields. To create a compound index, you use the createIndex() method with (httos://wev.nongodbtutorial .org/mongodb- indexes /mongodb-createindex/ ) the following syntax: db. collection. createIndex({ field1: type, field2: type, field3: type, 154 In this syntax, you specify a document that contains the index keys (field1, field2, field3...) and index types. 418 tn hanendinal ase 3t0723, 10:52AM The type describes the kind of index for each index key. For example, type 1 specifies an index that sorts items in ascending order while -1 specifies an index that sorts items in descending order. MongoDB allows you to create a compound index that contains a maximum of 32 fields. It's important to understand that the order of the fields specified in a compound index matters. If a compound index has two fields: field1 and field2, it contains the references to documents sorted by field1 first. And within each value.of field1, it has values sorted by field2. Besides supporting queries that match all the index keys, a compound index can support queries that match the prefix of the index fields. For example, if a compound index contains two fields: field1 and field2, it will support the queries on: © field1 * field1 and field2 However, it doesn’t support the query that matches the field2 only. MongoDB compound index example Let's take the example of using compound indexes. First, create a compound index on the ‘title and year fields of the movies collection: tine naa manana tnt enimanandiindavacimaannathenmrninsiday) 10723. 1052 AM Mongo08 Compound Inox db.movies.createIndex({ title 1 Output: title_1_year_1 Second, find the movies whose titles contain the word valley and were released in the year 2014: db.movies.find({title: /valley/gi, year: 2014}).explain('exect _—_—_—— Output: inputStage: { stage: 'IXSCAN', filter: { title: "$regex': ‘valley’, ‘$options': ‘is nReturned: 3, indexName: ‘title_1_year_1', The query uses the index title_1_year_1 instead of scanning the whole collection to find the result. aevhindarestmonnerterevsi ines! a nadine iannandinn Ldas——— 310123, 1052AM Mongo08 Compound Index Third, find the movies whose titles contain the word valley : db.movies.find({title:/valley/gi}).explain( ‘executionStats '); aS Output: inputStage: { stage: ‘IXSCAN', filter: { title: { '$regex': ‘valley’, ‘$options’: ‘is nReturned: 21, 5 indexName: ‘title_1_year_1', —_— Oe This query matches the title only, not the year. However, the query optimizer still makes use of the title_1_year_1 index. Finally, find the movies that were released in the year 2014: db.movies.find({year: 2014}) explain( ‘executionStats'); Output: executionStages: { | atom manning rolnnaananineavesimnandecmncnitsnnd! as | 3/10/23, 10:52 Ant Mongo! Compound Index stage: 'COLLSCAN’, filter: { year: { 'heq': 2014 } } nReturned: 1147, In this example, the query optimizer doesn't use the title_1_year_1 index but scan the whole collection ( CoLLSCAN ) to find the matches. Summary * Acompound index contains the references to multiple fields of a collection. ¢ Use the db.collection.createIndex() method to create a compound index. . © The order of fields in the index is important. ee arnimannndtvindavacimannadhamninrinday! as | yt0123, 10:52 AM ongoDD Ur \ mongoDB PTUTOR MongoDB Unique Index Summary: in this tutorial, you'll learn about unique indexes and how to use them to enforce the uniqueness of values for a field across documents in a collection. Introduction to the MongoDB unique index Often, you want to ensure that the values of a field are unique across documents in a collection, such as an email or username. A unique index can help you to enforce this rule. In fact, MongoDB uses a unique index to ensure that the _id is a unique primary key. a aa ee ee To create a unique index, you use the createIndex() method with the option {unique: true} like this: db.collection.createIndex({ field: 1}, funique: true}); MongoDB unique index examples Let's take some examples of using a unique index. 1) Create a unique index for a field 3/1028, 10:52.AM : MongoO'8 Unique index First, Inserts two documents into the users collection: db. users. insertMany (| { email: [email protected]", name: "john"}, {-email: 13 “[email protected]", name: "jane"}, Second, create a unique index for the email field: db.users.createIndex({email ique : true})5 Third, attempt to insert a new document with the email that already exists: db.users.insertOne( { email: "[email protected]", name: "johny"} 3 MongoDB returned the following error: MongoServerError: £11000 duplicate key error collection: mflix —_—— 2) Create a unique index for collection with duplicate data First, drop the users collection and recreate it by inserting three entries: db.users.drop() Jmnnnadinsndevesimnnnneiunic sande on bitnestua mannan re > = le UU ‘3710/28, 1052AM Hongob8 Unig Index db.users. insertMany( [ {-email: "[email protected]", name: "john"}, email: "“[email protected]", name; “johny"}, J { email: "[email protected]", name: "“jane"}, }) Second, attempt to create a unique index for the email field of the users collection: db.users.createIndex({email: 1},{unigque:true}) MongoDB returned the following error: MongoServerError: Index build failed: 95f78956-dSd@-4882-bfe@- Co The reason is that the email has duplicate entries [email protected] . RS Typically, you create a unique index on a collection before inserting any data. By doing this, you ensure uniqueness constraints from the start. If you create a unique index on a collection that contains data, you run the risk of failure because the collection may have duplicate values. When duplicate values exist, the unique index creation fails as shown in the previous example. To fix this, you need to review data and remove the duplicate entries manually before creating the unique index. For example: First, delete the duplicate user: Inte tha neil ce a wy 31028 05240 ong Une ne db.users.deleteOne({name:'johny', email: ‘[email protected]’}); Output { acknowledged: true, deletedCount: 1 } Then, create a unique index for the email field: db.users.createIndex({email: 1},{unique:true}) Output: email_1 Unique compound index When a unique index contains more than one field, it is called a unique compound index. A unique compound index ensures the uniqueness of the combination of ‘fields. mple, if you create a unique compound index for the field1 and field2, For exa the following values are unique: field1 field2 Combination 1 1 _ 1) 1 2 (1,2) See OOO OSS SESSCUVOECUVUGEUVUEOVEECEUTUEUS 6 oe y23, 1052 AM srs. MongoDB Unique Index ) > field field2 Combination : Ve 1 21) aa 2 (22) > However, the follcwing values are duplicate: | field1 field2 Combination : 1 1 (1,1) Fd 1 (1,1) -> duplicate 2 1 (2,1) 2 1 (2,1) -> duplicate To create a unique compound index, you specify fields in the index specification like this: db.colletion.createIndex({field1: 1, field2: 1}, {unique: trv Let's take the example of using the unique compound index. First, create a locations collection by adding one location to it: db.locat ic nsertone({ ) idress: “Downtown San Jose, CA, USA", Inttne:tiwnuaw manandbnstericd © santvindeuastmannndhsnitsinds) en anos, 10:52AM Mongo08 Unique index 37335480, -121.893028 3) Second, create a unique compound index for the lat and long fields of the locations collection: db. loca’ createIndex({ },{ unicve: true }); Output: lat_i_long a Third, insert 4 jocation with the lat value that already exists: db. locations. insertone({ ess: "Dev Bootcamp, San Jose, CA, USA", 37335480, -122.893028 }) It works becs\ise the let_1_long_1 index only checks the duplicate of the combination of lat and long values. tnetanew manath 3110723, 10.52 AM * Finally, att , exists: db. loc }) MongoDB i MongoSe Cc Summe ¢ Aunic collect © Aunig value © Use th create ongoDB Unique Index ‘o insert a location with the lat and long that already rsertone({ 5: "Central San Jose, CA, USA", 7.335480, -121.893028 the following error: or: £110@@ duplicate key error collection: mflix ey enforces the uniqueness of values for a field in a >mpound index enforces the uniqueness of combination of 'e fields in a collection. ceIndex() method with the option { unique: true } to index and compound unique index.

You might also like