MongoDB database index management method and mongodb Management Method

Source: Internet
Author: User
Tags stem words

MongoDB database index management method and mongodb Management Method
MongoDB index is a special data structure. indexes are stored in a dataset that is easy to traverse and read. indexes are a structure that sorts values of one or more columns in a database table;

Advantages of using indexes:Indexes can greatly improve the query efficiency. This is because the indexes are stored in the memory, and the index traversal efficiency must be higher for normal sets;
The cost of using indexes:Additional operation Overhead: you also need to perform index operations when performing insert, update, and delete operations. It is not cost-effective to use indexes for a set with few queries and many changes; extra memory overhead. Because the index is stored in the memory, you should ensure that the index size does not exceed the memory limit (if the index size is limited by memory, mongodb will delete some indexes, leading to performance degradation );
Mongdb indexes have the following restrictions:The number of indexes in a set cannot exceed 64;
The index name cannot exceed 128 characters;
A composite index can be up to 31;

The following query cannot be used for an index:Regular Expression query, $ regex; non-operator query, such as $ nin and $ not; arithmetic operators, such as $ mod; $ where operator clause;

You can create an index for a set.EnsureIndex ({ : <1 |-1> },{ }) Key: The key used by the index. 1 indicates the forward direction and-1 indicates the reverse direction;
Option: acceptable parameters. The parameter list is as follows:
Background: -Whether creating an index will block other database operations. The default value is false; Name: -? The index name. If not specified, mongodb generates an index name based on the index field name and sorting order; Unique: -Whether the index is unique. The default value is false; DropDups: -Whether duplicate records are deleted when a unique index is created. The default value is false; Sparse: -Whether or not to enable the index for fields that do not exist in the document. If it is set to true, no Index containing the corresponding field is displayed in the index field. The default value is false; ExpireAfterSeconds: -Set the TTL of the query set in memory ); V: -The version number of the index. The default version is the version used when the mongo index is created; Weights: -The weight of the index, which indicates the score weight of the index for other index fields. The value range is []. Default_language: -Specify the la s of the rules for disabling words, stem words, and word machines in text indexes. The default value is en english; Language_override: -Specify the field name in the document for text indexing and the language to overwrite the default language. The default value is language; ?

# Create an index for the col set. The index field is title and positive
db.col.ensureIndex( {title:1} )
# Create a composite index for the col set. The index fields are title, score, forward and forward.
db.col.ensureIndex( {title:1, score:1} )
# Create a cable backend
db.col.ensureIndex( {title:1}, {backgroud:true} )

Index overwrite query after an index is created, if the queried field has already been indexed when mongodb performs an index, mongodb does not actually query these fields in the database, instead, extract data directly from the created index (which is much faster than querying directly in the database). That is, mongodb uses the index to overwrite the query. Note that, by default, the _ id field is returned for mongodb queries. If the _ id field is not indexed, The _ id field is not overwritten ;?
Db. col. ensureIndex ({title: 1, score: 1 })? # Create an index for the title and score fields in the col set;
Db. col. find ({title: "hello world"}, {score: 1, _ id: 0}) # This query will be overwritten by the above index, and mongodb will query it directly in the index;
Db. col. find ({title: "hello world" },{ score: 1 })? ? ? ? # This index is not overwritten by the above indexes. mongodb queries the database because it contains the _ id field not covered by the index;
Db. col. find ({title: "hello world "})? ? ? ? ? ? ? ? ? # The index is not covered by the above index because it contains the _ id field not covered by the index;
※For the following types of queries, indexes cannot be used to overwrite the query:
The index field is an array;
The index field is a sub-document;

Index Array fields? Suppose you want to retrieve the tages array of the following user documents :?
{ ?
 ? "name":"assad",
 ? "tags": [
 ? ? ?"coder",
 ? ? ?"fat nerd",
 ? ? ?"philosophy♂"
 ? ]
 }
You can use the following name to create an array index. After creating an index for the entire array, an index is created separately for all values in the group:
?
> db.users.ensureIndex( {tages:1} )
Verify the search result :?
> db.users.find( {tages:"coder"} ).explain()

Index the sub-document fields. Assume that you want to retrieve the address sub-Documents of the following user documents, and create a user search using the city, state, and pincode fields. Because these fields are the address fields of the sub-document of the user, you need to create a search for the address document:
?
{ ?
 ? "name":"assad",
 ? "address": {
 ? ? ?"city": "Guanzhou",
 ? ? ?"state": "Guangdong",
 ? ? ?"pincode": "510000"
 ? }
 }
You can use the following to create an index for all fields in the address sub-document :?
> db.users.find( {address.city:1, address.state:1, address.pincode:1} )
Verify search results:
?
> db.users.find( {address.city:"Guangdong", address.state:"Gunagzhou" } ).explain()

View and delete indexes?
# View all indexes in the database
> db.system.indexs.find()
.....
?
# Viewing indexes in a set
> db.col.getIndexes()
[
 ? {
 ? ? ? "v" : 2,
 ? ? ? "key" : {
 ? ? ? ? ? "_id" : 1
 ? ? ? },
 ? ? ? "name" : "_id_",
 ? ? ? "ns" : "testdb.articles"
 ? },
 ? {
 ? ? ? "v" : 2,
 ? ? ? "key" : {
 ? ? ? ? ? "title" : 1
 ? ? ? },
 ? ? ? "name" : "title_1",
 ? ? ? "ns" : "testdb.articles"
 ? }
]
?
# View the index size, in bytes
> db.articles.totalIndexSize()
53248
?
# Deleting all indexes
> db.articles.dropIndexes()
?
# Deleting an index with a specified name
> db.srticles.dropIndex("title_1")

Index query analysis Explain () method? You can use the explain () method to obtain the query information, index usage, query statistics, and other information to optimize the index ;?
> Db. articles. ensureIndex ({author: 1, title: 1 })? ? # Creating an index
> Db. articles. find ({author: "assad" },{ title: 1, _ id: 0}). explain ()? ? # Use the explain function for query and Analysis
The index-related information in the returned information is :?
 ?"inputStage" : {
 ? ? ?"stage" : "IXSCAN",
 ? ? ?"keyPattern" : {
 ? ? ? ? ? ? ?"author" : 1,
 ? ? ? ? ? ? ?"title" : 1
 ? ?  },
 ? ? ?"indexName" : "author_1_title_1",
 ? ? ?"isMultiKey" : false,
 ? ? ?"multiKeyPaths" : {
 ? ? ? ? ? ? ?"author" : [ ],
 ? ? ? ? ? ? ?"title" : [ ]
 ? ?  },
 ? ? ?"isUnique" : false,
 ? ? ?"isSparse" : false,
 ? ? ?"isPartial" : false,
 ? ? ?"indexVersion" : 2,
 ? ? ?"direction" : "forward",
 ? ? ?"indexBounds" : {
 ? ? ? ? ? ? ?"author" : [
 ? ? ? ? ? ? ? ? ? ? ?"[\"assad\", \"assad\"]"
 ? ? ? ? ? ?  ],
 ? ? ? ? ? ? ?"title" : [
 ? ? ? ? ? ? ? ? ? ? ?"[MinKey, MaxKey]"
 ? ? ? ? ? ?  ]
 ? ?  }
  }
Hint () method
The hint () method is used to force mongodb to use a specified index. You can also use the explain () method to analyze the following indexes ;?
>db.users.find({author:'assad'},{title:1,_id:0}).hint({author:1,title:1})

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.