Index introduction to the MongoDB tutorial

  • 2020-05-12 06:25:03
  • OfStack

1. Basis of index:

MongoDB's indexes are almost identical to traditional relational databases, including some basic optimization techniques. Here is the command to create the index:


    > db.test.ensureIndex({"username":1})
 

You can check whether the index has been successfully established by the following name:

    > db.test.getIndexes()
 

The command to drop the index is:

    > db.test.dropIndex({"username":1})
 

In MongoDB, we can also create composite indexes, such as:

    -- digital 1 said username The index of the key is stored in ascending order, -1 said age The index of the key is stored in descending order.
    > db.test.ensureIndex({"username":1, "age":-1})
 

Once the index is created, the index will be used by queries based on username and age, or by queries based on username, but the composite index will not be used by queries based on age alone. It can therefore be said that if you want to use a composite index, you must include the first N index columns in the composite index in the query criteria. However, if the order of key values in the query criteria is not the same as the order of creation in the composite index, MongoDB can intelligently help us adjust the order so that the composite index can be used by the query. Such as:

    > db.test.find({"age": 30, "username": "stephen"})
 

For the query criteria in the example above, MongoDB will dynamically adjust the order of the query criteria documents before retrieving them so that the query can use the composite index just created.
We can create indexes for embedded documents with the same rules as normal documents, such as:

    > db.test.ensureIndex({"comments.date":1})
 

For the index created above, MongoDB will automatically assign an index name to the newly created index according to the keyname and index direction of the index. The following command can specify an index name for the newly created index at the time of index creation, such as:

    > db.test.ensureIndex({"username":1},{"name":"testindex"}) 
 

As the collection grows, you need to index for a large number of sorts in the query. If sort is not called on the key of the index, MongoDB needs to extract all the data into memory and sort it. So when you do indexless sorting, MongoDB will report an error if the amount of data is too large to be sorted in memory.

2. Exclusive index:
Indexes created by default are not one-only indexes. The following example creates a unique index, such as:

    > db.test.ensureIndex({"userid":1},{"unique":true})
 

If you insert a duplicate userid document again, MongoDB will report an error to prompt you to insert the duplicate key, as follows:

    > db.test.insert({"userid":5})
    > db.test.insert({"userid":5})
    E11000 duplicate key error index: test.test.$userid_1  dup key: { : 5.0 }   
 

If the inserted document does not contain the userid key, then the value of the key in the document is null. If similar documents are inserted multiple times, MongoDB will report the same error, such as:

    > db.test.insert({"userid1":5})
    > db.test.insert({"userid1":5})
    E11000 duplicate key error index: test.test.$userid_1  dup key: { : null }  
 

If duplicates already exist when creating a unique index, we can use the following command to help us eliminate duplicates when creating a unique index and keep only the first document found, such as:
-- first, delete the unique index you just created.

    > db.test.dropIndex({"userid":1})
    -- Insert test data to ensure that duplicate keys exist in the collection.
    > db.test.remove()
    > db.test.insert({"userid":5})
    > db.test.insert({"userid":5})   
    -- Create only 1 Index and eliminate duplicate data.
    > db.test.ensureIndex({"userid":1},{"unique":true,"dropDups":true})   
    -- The query result confirms that the duplicate key was indeed dropped when the index was created.
    > db.test.find()
    { "_id" : ObjectId("4fe823c180144abd15acd52e"), "userid" : 5 }   
   

We can also create a compound 1-only index, ensuring that the compound key is only 1. Such as:

    > db.test.ensureIndex({"userid":1,"age":1},{"unique":true})   
   

3. Use explain:
explain is a very useful tool that will help you get useful information about your queries. You can get the query details simply by calling the method on the cursor. explain returns a document instead of the cursor itself. Such as:


    > db.test.find().explain()
    {
        "cursor" : "BasicCursor",
        "nscanned" : 1,
        "nscannedObjects" : 1,
        "n" : 1,
        "millis" : 0,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : false,
        "indexOnly" : false,
        "indexBounds" : {         }   
    }
 

explain returns statistics about the indexes used by the query, the time taken, and the number of documents scanned.
"cursor":"BasicCursor" means no index is used.
"nscanned":1 indicates how many documents have been queried.
"n":1 represents the number of documents returned.
"millis":0 represents the time taken for the entire query.

4. Index management:

The system.indexes collection contains the details of each index, so you can query the existing index with the following command:


    > db.system.indexes.find()
 

If you are indexing documents with existing data, you can execute the following command to enable MongoDB to create indexes in the background so that no other operations are blocked during creation. By contrast, creating the index in a blocking fashion makes the entire creation process more efficient, but at the time of creation MongoDB will not be able to receive other operations.

    > db.test.ensureIndex({"username":1},{"background":true})
 


Related articles: