An index is a special data structure that is stored in a collection of data that is easy to traverse (the index is stored in a specific field or the value of a field set) and uses a B-tree structure. Indexes can greatly improve MongoDB query efficiency. If there is no index, MongoDB must perform a full collections scan, that is, scan every document in the collection and select the document that meets the query criteria. MongoDB can use indexes to limit the number of documents it must query if appropriate indexes exist, especially when dealing with large amounts of data, so choosing the right indexes is critical and important.

To create an index, consider the following:

  • Each index requires at least 8KB of data space;
  • Adding indexes has some performance impact on write operations. For Collections with high write rates, indexes are expensive because each insert must also update any index;
  • Indexes are good for Collections with high read rates and do not affect unindexed queries;
  • When indexes are in the action state, each index consumes disk space and memory, so you need to track this.

Index restrictions:

  • The length of the index name cannot exceed 128 fields;
  • The composite index cannot exceed 32 attributes;
  • No more than 64 indexes per Collection;
  • Different types of indexes also have their own limitations.

1. Index management

1.1 Index Creation

Index creation uses the createIndex() method in the following format:

db.collection.createIndex(<key and index type specification>,<options>)
Copy the code

CreateIndex () accepts optional parameters, which are listed as follows:

Parameter Type Description
background Boolean The index creation process blocks other database operations. Background specifies how to create an index in the background. The default value of “background” is false.
unique Boolean Whether the created index is unique. Specifies true to create a unique index. The default value is false.
name string The name of the index. If not specified, MongoDB generates an index name from the join index’s field name and sort order.
dropDups Boolean Version 3.0+ is not available. Whether to delete duplicate records when creating unique indexes, specifying true to create unique indexes. The default value is false.
sparse Boolean Disable indexing for field data that does not exist in the document; This parameter is important because if set to true, documents that do not contain the corresponding field will not be queried in the index field. The default value is false.
expireAfterSeconds integer Specify a value in seconds to complete the TTL setting and set the lifetime of the collection.
v index version The version number of the index. The default index version depends on the version mongod was running when the index was created.
weights document Index weight value. The value between 1 and 99,999 represents the score weight of this index relative to other index fields.
default_language string For text indexing, this parameter determines the list of stop terms and rules for stems and lexical devices. Default: English
language_override string For text indexes, this parameter specifies the name of the field to be included in the document, overriding the default language, which is language.

1.2 Viewing Indexes

View all indexes in the Collection in the following format:

db.collection.getIndexes()
Copy the code

1.3 Deleting an Index

Delete an index from a Collection:

Db. Collection. DropIndexes () / / delete all index db. The collection. The dropIndex () / / delete the specified indexCopy the code

1.4 Index Name

The default index name is the index key and value1 or -1 for each key in the index, of the form index_name+1/-1, for example:

Db.products.createindex ({item: 1, quantity: -1})---- the index name is item_1_quantity_-1Copy the code

You can also specify the index name:

Db.products.createindex ({item: 1, quantity: -1}, {name: "inventory"}) ----Copy the code

1.5 Viewing and Terminating Index Creation Process

methods parsing
db.currentOp() View the index creation process
db.killOp(opid) Terminates index creation. -opid is the operation ID

1.6 Index Usage

In the form of parsing
$indexStats Get index access information
explain() Return the query: Use the db.collection.explain () or cursor.explain () methods in executionStats mode to return statistics about the query process, including the indexes used, the number of documents scanned, and the time it took to process the query in milliseconds.
Hint() Control indexes, for example, to force MongoDB to use a specific index for db.collection.find (), use the hint () method to specify the index

1.7 MongoDB Metrics

MongoDB provides a number of metrics for index usage and operation that may need to be considered when analyzing database index usage, as shown below:

In the form of parsing
metrics.queryExecutor.scanned The total number of index items scanned during the query and query plan evaluation
metrics.operation.scanAndOrder Returns the total number of queries for sorted numbers that cannot be used to perform a sort operation with the index
collStats.totalIndexSize The total size of all indexes. The scale parameter affects this value. If the index uses prefix compression (which is the default for WiredTiger), the returned size will reflect the compression size of any such index when the total is calculated.
collStats.indexSizes Specifies the key and size of each existing index on the collection. The scale parameter affects this value
dbStats.indexes Contains a count of the total number of indexes for all collections in the database.
dbStats.indexSize The total size of all indexes created on this database

1.8 Background Index Operations

Index creation on a dense Collection: By default, creating an index when a dense Collection is nearing database maximum prevents other operations. When indexes are created for dense collections that are nearing database maximum capacity, the database holding the Collection is not available for read or write operations until the index build is complete. Any operation that requires a read or write lock on all databases, such as listDatabases, will wait for an index build that is not a background process to complete.

Therefore, you can use the background property to set the background index creation as follows:

db.people.createIndex( { zipcode: 1 }, { background: Db.people.createindex ({zipcode: 1}, {background: {db.people.createIndex({zipcode: 1}, {background: true, sparse: true } )Copy the code

2. Index type

2.1 Single Field Indexes

MongoDB can create indexes in any of the fields, and by default, all collections create indexes in the _ID field. The _id index is used to prevent clients from inserting documents with the same value as the _ID field, and the _ID field index cannot be deleted. The _ID index is used in a shard cluster. If the _ID field is not used as a shard key, the application must ensure that the values in the _ID field are unique to prevent errors. The solution is to use standard, automatically generated ObjectId. In the value of a general single-field index, “1” specifies the index that sorts items in ascending order, and “-1” specifies the index that sorts items in descending order. As follows:

Create an index on a single field as shown in the following example:

{ "_id": ObjectId("570c04a4ad233577f97dc459"), "score": 1034, "location": { state: "NY", city: Db.records.find ({score: 1}) // Create a single index db.records.createIndex({score: 1}) // Support db.records.find({score: 1}) 2 } ) db.records.find( { score: { $gt: 10 } } )Copy the code

Create an index for a field in an embedded Document as shown in the following example:

Db.records. CreateIndex ({"location.state": 1}) // Support db.records. Find ({"location.state": 1}) "CA" } ) db.records.find( { "location.city": "Albany", "location.state": "NY" } )Copy the code

Create an index on an embedded Document as shown in the following example:

Db.records. Find ({location: {city: "New York", state: "NY"}}) db.records. Find ({location: {city: "New York", state: "NY"}})Copy the code

2.2 Compound Index

Composite indexing refers to combining multiple keys together to create an index, which speeds up queries that match multiple keys. Features are as follows:

  • MongoDB limits any composite index to 32 fields;
  • Unable to create a composite index with hash index type. An error is reported if you try to create a compound index that contains a hash index field;
  • The order in which composite indexes create field indexes is important. Because indexes store references to fields in ascending (1) or descending (-1) sort order; For single-field indexes, the sort order of the keys doesn’t matter, because MongoDB can traverse the index in either direction. However, for composite indexes, the sort order determines whether the index can support sort operations;
  • In addition to supporting queries that match on all index fields, composite indexes can also support queries that match the prefix of an index field.

Create a compound index in the following format:

db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... })Copy the code

Index {userID: 1, score: -1}, index{userID: 1, score: -1}, index{userID: 1, score: -1} The diagram below:

Create a composite index as shown in the following example:

{ "_id": ObjectId(...) , "item": "Banana", "category": ["food", "produce", "grocery"], "location": "4th Street Store", "stock": 4, "type": Db.products.createindex ({"item": 1, "stock": 1}) db.products.find({item: "Banana" } ) db.products.find( { item: "Banana", stock: { $gt: 5 } } )Copy the code

Prefix query in a composite index as shown in the following example:

Db.products.createindex ({"item": 1, "location": 1, "stock": 1}) // Create a compound index db.products.createIndex({"item": 1, "location": 1, "stock": 1}) Db.products. find({item: "Banana"}) db.products.find({item: "Banana", location: Db.products.find ({location: "Beijing"}) db.products.find({stock: {$gt: Find ({location: "Beijing", stock: {$gt: 5}) db.products.find({location: "Beijing", stock: {$gt: 5}) "Beijing", item: "Banana"},stock: {$gt: 5})Copy the code

2.3 Multi-key Indexes

MongoDB uses multi-key indexes to create indexes for each element of the array. Multi-key indexes can be built on strings, numbers and other keys or arrays embedded with documents. If the index fields contain array values, MongoDB will automatically determine whether to create multi-key indexes. You do not need to specify the multi-key type manually. The creation mode is as follows:

db.coll.createIndex( { <field>: < 1 or -1 > } )
Copy the code

Index boundary With multi-key indexes, the index boundary (the index boundary is the range that the index can look up in the query process) will be calculated, and the calculation must follow some rules. That is, when the fields in multiple query conditions all have indexes, MongoDB will use intersection or union to determine the boundary of these conditional index fields and finally generate a minimum search range. Intersection boundary An intersection boundary is a logical intersection of multiple boundaries. For a given array field, suppose a query uses multiple conditional fields of the array and can use a multi-key index. If $elemMatch is used to join the conditional field, MongoDB will intersect the multi-key index boundary as shown in the following example:

{_id: 1, item: "ABC", ratings: [2, 9]} {_id: 2, item: "XYZ", ratings: [4, 3]} // Create multi-key index on ratings array: Db.survey. Find ({ratings:{$elemMatch:{$Gte :3,$LTE :6}}) db.survey. Find ({ratings:{$elemMatch:{$Gte :3,$LTE :6}}) { ratings : { $gte: 3, $lte: 6 } } ) //(2)Copy the code

The query conditions are greater than or equal to 3 and less than or equal to 6 respectively, where $elemMatch is used in (1), resulting in an intersection ratings: [[3,6].

Union boundary The union boundary is often used to determine the boundary of a multi-key combination index. For example, given a combination index {a:1,b:1}, there is a boundary on field A: [3, +∞), and there is a boundary on field B: (-∞, 6). The result of the two boundaries is {a: [[3, Infinity]], b: [[-infinity, 6]]}

And if MongoDB cannot combine these two boundaries, MongoDB will force the index scan to use the boundary of the first field of the index, in this case: a: [[3, Infinity]].

A combined index field is an array, such as a Survey Collection document that contains the item field and ratings array fields, as shown in the following example:

{ _id: 1, item: "ABC", ratings: [ 2, 9 ] } { _id: 2, item: "XYZ", ratings: [4, 3]} db.survey. CreateIndex ({item: 1, ratings: Db.survey. Find ({item: "XYZ", ratings: {$gte: 3}})Copy the code

Query conditions to be processed respectively:

item: "XYZ" -->  [ [ "XYZ", "XYZ" ] ];
ratings: { $gte: 3 } -->  [ [ 3, Infinity ] ].
Copy the code

MongoDB uses union boundaries to combine these two boundaries:

{ item: [ [ "XYZ", "XYZ" ] ], ratings: [ [ 3, Infinity ] ] }  
Copy the code

If you want to create an index on an array containing the document field, use a comma “, “in the index declaration to separate the field names, as shown in the following example:

ratings: [ { score: 2, by: "mn" }, { score: 9, by: "anon" } ]
Copy the code

The score field name is ratings.score.

5). Mix the union of fields that are not array types with fields of array types

{ _id: 1, item: "ABC", ratings: [ { score: 2, by: "mn" }, { score: 9, by: "anon" } ] } { _id: 2, item: "XYZ", ratings: [ { score: 5, by: "anon" }, { score: 7, by: "Wv"}}] / / in the item ratings and array field. The score and ratings. By creating a composite index db. The survey2. CreateIndex ({" item ": 1," ratings. Score ": Find ({item: "XYZ", "ratings.score": {$LTE: 5}, "ratings.by": "anon"})Copy the code

The query conditions are processed respectively:

item: "XYZ"--> [ ["XYZ","XYZ"] ];
score: {$lte:5}--> [[-Infinity,5]];
by: "anon" -->["anon","anon"].
Copy the code

MongoDB can combine the item key boundary with either ratings.score or ratings.by boundary, depending on the query criteria and the value of the index key. MongoDB cannot ensure which boundary and item fields are union. But if you want to combine ratings.score and ratings.by boundaries, the query must use $elemMatch.

6). The union boundary of the array field index is the boundary of the union index key inside the array.

  • The index key must have the same field path except for the field name,
  • The value of $elemMatch must be specified on the path
  • For embedded documents, use comma-separated paths, such as A.B.C.D for field D. To combine the index key boundaries on the same array, $elemMatch must be used on the A.B.C path.

For example: create composite indexes on ratings.score and ratings.by fields:

db.survey2.createIndex( { "ratings.score": 1, "ratings.by": 1 } )
Copy the code

The fields ratings.score and ratings.by have the same path ratings. The following query using $elemMatch requires that the ratings field must contain an element that matches both conditions:

db.survey2.find( { ratings: { $elemMatch: { score: { $lte: 5 }, by: "anon" } } } )
Copy the code

The query conditions are processed respectively:

score: { $lte: 5 } --> [ -Infinity, 5 ];
by: "anon"--> [ "anon", "anon" ].
Copy the code

MongoDB can combine these two boundaries using union boundaries:

{ "ratings.score" : [ [ -Infinity, 5 ] ], "ratings.by" : [ [ "anon", "anon" ] ] }  
Copy the code

$elemMatch (); $elemMatch (); $elemMatch ();Official documentation -Multikey Index Bounds”.


Limitations:

  • For a composite multi-key index, each index document can have at most one index field whose value is an array. If the composite multi-key index already exists, this restriction cannot be violated when inserting documents;
  • You cannot declare a multi-key index as a shard-key index.
  • Hash indexes cannot have multi-key indexes;
  • Multi-key indexes cannot perform overwrite queries;
  • When a query declaration considers the entire array as an exact match, MongoDB can use a multi-key index to find the first element of the query array, but cannot use a multi-key index scan to find the entire array. Instead, after the first element of the array is queried using a multi-key index, MongoDB performs another array match on the filtered document.

2.4 Text Index

MongoDB provides a full-text index type that supports searching string contents in collections and creating full-text searchable indexes of strings and arrays of strings. These full-text indexes do not store language-specific stop words (such as “the”, “a”, “or”) and prevent words in the document set from storing only root words. The creation method is as follows:

Db. Collection. CreateIndex ({key: "text", the key: "text"... })Copy the code

And MongoDB provides the creation of weights and wildcards. Search mode Multiple character strings are separated by Spaces. Use – to exclude query, as shown in the following:

db.collection.find({$text:{$search:"runoob add -cc"}})
Copy the code

To drop the full index, you pass the name of the index to the db.collection.dropIndex() method, and to get the name of the index, use the db.collection.getIndexes () method.

You can also specify the language for the full-text index, either at creation time through the default_language attribute, or override the default language for document document creation using the language_override attribute, as follows:

/ / methods: specify different language to use when creating a full-text index default_language attribute the collections. CreateIndex ({content: "text"}, {default_language: "Spanish"}) // Override the default language db.quotes.createIndex({quote: "text"}, {language_override: "Idioma"}) / / the default name of full-text index for context_text, users.com ments. Text, MyTextIndex db. The specified name collection. CreateIndex ({the content: "text", "users.comments": "text", "users.profiles": "text" }, { name: "MyTextIndex" } )Copy the code

Weights Each full-text index can assign different degrees of search by setting a weight, the default weight being 1. For each index field in the document, MongoDB multiplies the number of matches by the weight and adds up the results. Using this sum, MongoDB then calculates the score for the document as shown in the following example:

{ _id: 1, content: "This morning I had a cup of coffee.", about: "beverage", keywords: [ "coffee" ] } { _id: 2, content: "Who doesn't like cake?" , about: "food", keywords: ["cake", "food", "dessert"]} db.blog.createIndex({content: "text", keywords: "text", about: "text" }, { weights: { content: 10, keywords: 5 }, name: "TextIndex" } )Copy the code

The weight of content is 10, the weight of keywords is 5, and the default weight of about is 1. Therefore, it can be concluded that the query frequency of content for keywords is more than 2 times, while that for about field is 10 times.

Wildcard full-text index When creating full-text indexes on multiple fields, you can also use the wildcard specifier ($**). Using wildcard full-text indexes, MongoDB will provide string data containing each Document in the Collection. Such as:

db.collection.createIndex( { "$**": "text" } )
Copy the code

A wildcard full index is a full index on multiple fields. Therefore, you can assign weights to specific fields during index creation to control the ranking of the results.

limit

  • One full-text index per Collection: a Collection has at most one full-text index,
  • The Text Search and Hints functions, and hint () cannot be used if the query contains a $Text query expression;
  • Text Index and Sort, the Sort operation cannot get the Sort order from a Text Index, even a composite Text Index; That is, the sort operation cannot use the sort in the text index;
  • Composite indexes: Composite indexes can include a combination of text index keys and ascending/descending index keys. However, these composite indexes have the following limitations:

    1). Composite text indexes cannot contain any other special index types, such as multi-key or geospatial index fields.

    2). If the compound text index includes the key before the text index key, the query predicate must contain the equality matching condition on the previous key when the $TEXT search is performed.

    3). When creating a composite text index, all text index keys must be listed adjacent to each other in the index specification document.

2.5 a Hash index

Hash indexes use hash functions to compute hash values of index field values. The hash function collapses the embedded document and evaluates the hash value of the entire value, but does not support multi-key (that is, array) indexes. The convertShardKeyToHashed() method is used to generate the hash index key. The creation method is as follows:

db.collection.createIndex( { _id: "hashed" } )
Copy the code

And hash indexes support sharding using hash shard keys. Hash based sharding uses the hash index of the field as the shard key to split the data in the entire shard cluster.

3. Index attributes

Index attributes include TTL index, unique index, partial index, sparse index, and case sensitive index.

3.1 TTL Indexes (TTL Indexes)

A TTL index is a special single-field index, and the field type must be date or contain an array with date type. MongoDB can use it to automatically delete documents from the collection after a certain time or at a specific clock time. Data expiration is useful for certain types of information, such as machine-generated event data, logs, and session information, that need only last a limited time in the database.

Create TTL index (expireAfterSeconds) create TTL index (expireAfterSeconds)

db.collection.createIndex( {key and index type specification},{ expireAfterSeconds: time})
Copy the code

Example:

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )
Copy the code

Specifying an expiration time starts by creating a TTL index on the field that holds a BSON date type value or an array of BSON date type objects and specifying expireAfterSeconds to 0. For each document in the collection, set the index date field to a value corresponding to the document expiration time. The following is an example: Step 1:

db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
Copy the code

The second step:

db.log_events.insert( { "expireAt": new Date('July 22, 2013 14:00:00'), "logEvent": 2, "logMessage": "Success!" })Copy the code

Data expiration type:

  • When the specified time reaches the expiration threshold, the data will expire and be deleted.
  • If the field is an array and there are multiple date values in the index, MongoDB uses the lowest (that is, earliest) date value in the array to calculate the expiration threshold.
  • If the index field in the document is not a date or an array containing date values, the document will not expire;
  • If the document does not contain index fields, the document will not expire.

TTL index specific restrictions:

  • A TTL index is a single-field index. Composite indexes do not support TTL and ignore the expireAfterSeconds option;
  • The _ID attribute does not support the TTL index.
  • Unable to create a TTL index on the upper bound set because MongoDB cannot remove documents from the upper bound set;
  • The createIndex() method cannot be used to change the expireAfterSeconds value of an existing index. Instead, the collMod database command is used in conjunction with the index collection flag. Otherwise, to change the value of an option for an existing index, you must first drop the index and recreate it;
  • If a non-TTL single-field index exists in a field, the TTL index cannot be created on the same field because different types of indexes cannot be created on the same key. To change a non-TTL single-field index to A TTL index, you must first drop the index and recreate it using the expireAfterSeconds option.

3.2 Unique Indexes

Unique indexes ensure that index fields do not store duplicate values; That is, enforce uniqueness of index fields. By default, MongoDB creates a unique index on the _ID field during collection creation. The creation method is as follows:

db.collection.createIndex( <key and index type specification>, { unique: true } )
Copy the code

The following is an example of creating a single field:

db.members.createIndex( { "user_id": 1 }, { unique: true } )
Copy the code

Unique composite indexes: You can also enforce unique constraints on composite indexes. If you use unique constraints on composite indexes, MongoDB enforces uniqueness on combinations of index key values. The following is an example:

// Create index and enforce uniqueness of groupNumber, lastName, and firstName values. db.members.createIndex( { groupNumber: 1, lastname: 1, firstname: 1 }, { unique: true } )Copy the code

Unique multi-key index:

{_id: 1, a: [{loc: "a", qty: 5}, {10} qty:]} / / create indexes: db. Collections. CreateIndex ({" a. oc ": 1," a.q ty ": 1}, {unique: true}) // Insert data: unique index allows the following Document to be inserted into the Collection because the index enforces a unique combination of a.oc and A.ty values: db.collection.insert({_id: 2, a: [ { loc: "A" }, { qty: 5 } ] } ) db.collection.insert( { _id: 3, a: [ { loc: "A", qty: 10 } ] } )Copy the code

Creating a unique index to a replica or shard: For replica sets and shard clusters, creating a unique index using a scrolling process requires stopping all writes to the collection during the process. Do not use a scrolling procedure if you cannot stop all writing to the collection during the procedure. Instead, build a unique index on the collection by:

  • On the master server to replicate set a db. Collections. CreateIndex ()
  • On mongos for shard cluster send out the collections. CreateIndex ()

NOTE: You can see the details

Limitations:

  • If the collection already contains data that is outside the unique constraint of the index (that is, duplicate data), MongoDB cannot create a unique index on the specified index field.
  • You cannot create a unique index on a hash index
  • The unique constraint applies to a Document in the Collection. Because the constraint applies to a single document document, for a unique multi-key index, a document may have array elements that cause duplicate index key values as long as the index key values of that document do not duplicate those of another document document. In this case, the duplicate index record inserts the index only once.
  • A shard Collection can only have the following unique indexes:

    1). Index on shard key

    2). Shard keys are compound indexes of prefixes

    3). Default _id index; However, if the _ID field is not a shard key or a shard key prefix, the _ID index only enforces a unique constraint for each shard. If the _ID field is neither a shard key nor a shard key prefix, MongoDB expects the application to enforce uniqueness of the _ID value in shards.

3.3 Partial Indexes

A partial index achieves a local search through a specified filter expression. Through the db. Collection. CreateIndex increase partialFilterExpression attributes () method, filter expressions are as follows:

  • Equation expressions (that is, file: value or using the $eq operator)
  • $exists expression
  • $gt, $Gte, $lt, $LTE
  • The $type expression
  • $and

The following is an example:

/ / create some index db. Restaurants. CreateIndex ({cuisine: 1, name: 1}, {partialFilterExpression: {rating: {$gt: Db.restaurants. Find ({cuisine: "Italian", rating: {$gte: 8 } } ) //(1) db.restaurants.find( { cuisine: "Italian", rating: { $lt: 8 } } ) //(2) db.restaurants.find( { cuisine: "Italian" } ) //(3)Copy the code

Among them:

  • $gte: 8} {$gt: 5} {$gte: 8} {$gt: 5} {$gte: 8} {$gt: 5} {$gte: 8} {$gt: 5} {$gte: 8} {$gt: 5} {$gte: 8} {$gt: 5} {$gte: 8} {$gt: 5}
  • (2) Query: if the conditions cannot reach the complete set, MongoDB will not use part of the index for query or sorting operations.
  • (3) Query: The secondary query does not use a filter expression, nor does it use a partial index, because to use a partial index, the query must include a filter expression (or a modified filter expression specifying a subset of the filter expression) as part of its query criteria

Limitations:

  • You cannot create multiple local indexes through filter expressions alone;
  • Local indexes and sparse indexes should not be used together.
  • The _id index cannot use a local index, and the shard key index cannot use a local index.
  • Specify both the partialFilterExpression and the unique constraint, and the unique constraint applies only to documents that satisfy the filter expression. If the Document does not meet the filtering criteria, a partial index with a unique constraint is allowed to insert a Document that does not meet the unique constraint.

3.4 Sparse Indexes

The sparse index searches only the entries of documents that contain indexed fields and skips documents where the index key does not exist, that is, the sparse index does not search for documents that do not contain a sparse index. By default, 2DSphere (version 2), 2D, geoHaystack, full-text indexes, etc are always sparse indexes. Way to create the db. Collection. CreateIndex increase sparse attributes () method, as shown below:

db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } )
Copy the code

Sparse index not used: If a sparse index would result in an incomplete result set for query and sort operations, MongoDB will not use the index unless hint() explicitly specifies the index.

Sparse composite index:

  • For sparse composite indexes with ascending/descending sort, the presence of a key index in the composite index will be detected
  • For a sparse composite index that contains geospatial capability with up/down sort, only the presence of a geospatial key can be detected
  • For sparse composite indexes that contain full-text indexes in ascending/descending order, only full-text indexes can be detected

Sparse indexes and uniqueness: An index that is both sparse and unique avoids duplicate documents on the collection, but allows multiple documents to ignore the key. Both constraints must be followed to satisfy sparse indexing and uniqueness operations.

The following is an example of integration:

{ "_id" : ObjectId("523b6e32fb408eea0eec2647"), "userid" : "newbie" } { "_id" : ObjectId("523b6e61fb408eea0eec2648"), "userid" : "abby", "score" : 82 } { "_id" : ObjectId("523b6e6ffb408eea0eec2649"), "userid" : "nina", "score" : Db.scores. CreateIndex ({score: 1}, {sparse: true}) db.scores. Find ({score: {$lt: 90 } } ) //(1) db.scores.find().sort( { score: -1 } ) //(2) db.scores.find().sort( { score: -1 } ).hint( { score: Db.scores. CreateIndex ({score: 1}, {sparse: true, unique: 1}) //(3) // createIndex on score field with unique constraint and sparse filter: db.scores. CreateIndex ({score: 1}, {sparse: true, unique: 1) True}) // This index allows you to insert documents with a unique value for the score field or documents that do not include the score field. Db. Scores. Insert ({"userid": "AAAAAAA", "score": 43}) db. Scores. 34 } ) db.scores.insert( { "userid": "CCCCCCC" } ) db.scores.insert( { "userid": Db. Scores. Insert ({"userid": "AAAAAAA", "score"); 82 } ) db.scores.insert( { "userid": "BBBBBBB", "score": 90 } )Copy the code

Among them:

  • {“_id” : ObjectId(” 523b6e61fb408EEA0EEC2648 “), “userID” : “Abby “, “score” : 82}
  • {“_id” : ObjectId(” 523b6e6FFB408EEA0EEC2649 “), “userID” : {” id” : ObjectId(” 523b6e6FFB408EEA0EEC2649 “); “nina”, “score” : 90 } { “_id” : ObjectId(“523b6e61fb408eea0eec2648”), “userid” : “abby”, “score” : 82 } { “_id” : ObjectId(“523b6e32fb408eea0eec2647”), “userid” : “newbie” }
  • Hint () : {“_id” : ObjectId(” 523b6e6FFB408EEA0EEC2649 “), “userID” : “Nina “, “score” : 90} {“_id” : ObjectId(“523b6e61fb408eea0eec2648”), “userid” : “abby”, “score” : 82 }

4. Other matters

4.1 Index Policy

Index policy:

  • The optimal index for an application must consider many factors, including the type of query expected, the ratio of reads to writes, and the amount of memory available on the system.
  • When developing an indexing strategy, you should have a deep understanding of your application’s queries. Before building indexes, map the types of queries that will be run so that you can build indexes that reference these fields. Indexes have a performance cost, but they are more valuable for frequent queries on large data sets. Consider the relative frequency of each query in the application and whether the query justifies the index.
  • The best overall strategy for designing indexes is to analyze the various index configurations using a dataset similar to the one you will run in production to see which configurations perform best. Review the current indexes created for the collection to ensure that they support your current and planned queries. If the index is no longer in use, delete it.
  • Typically, MongoDB uses only one index to complete most queries. However, each clause of $or query may use a different index, and starting with 2.6, MongoDB can use the intersection of multiple indexes.

4.2 the following

There will also be MongonDB index optimization, copy set and sharding summary, the most important will also be summarized in the use of MongoDB combat and combat process of some pits, can pay attention to the follow-up update MongoDB series.

Finally, you can pay attention to the public number, learning together, every day will share dry goods, and learning video dry goods!