Getting started with mongoDB indexes quickly

mongo can increase the speed of queries by creating indexes

       insert image description here


1. Getting Started and Preparing Data

Start mongo and select the target database

mongo
use test

Then prepare a set of data (100,000 pieces of data, a larger amount of data)

for(i=0;i<100000;i++){db.test.insert({name:'test'+i,age:i})}

insert image description here


2. Before creating an index

Query the data whose name is "test90000". And use the explain method to see the performance of the query.

db.test1.find({name:"test90000"}).explain('executionStats')

insert image description here
Here you can see that the query took 53ms


3. Create index createIndex

Create an index on the field name

db.test1.createIndex({name: 1})

insert image description here
Check out the index:

insert image description here
Before creating an index for name, the _id field defaults to the index. After the creation, the collection has two indexes, "_id" and "name".


4. After creating the index

Find the piece of data again, and look at the performance of the query, and find that the time taken is close to 0 milliseconds. That is, the query performance is greatly improved after the index is set.

db.test1.find({name:"test90000"}).explain('executionStats')

insert image description here


5. Delete the index

db.test1.dropIndex({name:1})

Check it out

db.test1.getIndexes()

insert image description here
As shown in the figure, only the "_id" index is left. The "name" index has been dropped.


6. Unique Index and Conformance Index

①Unique index

db.test1.createIndex({name: 1},{"unique":true})

insert image description here
view index

db.test1.getIndexes()

insert image description here
As you can see, unique is true.

After setting as a unique index, the value of the index cannot be repeated.
(This feature can also be used to achieve the purpose of deduplication when writing crawlers that do not want duplicate data in a field.)

When inserting a piece of data with a duplicate name as shown in the figure, the following error will be reported:
insert image description here
that is, the insertion failed.


②Compound index

The way of creating multiple indexes is called compound index.

First delete the index name just created

db.test1.dropIndex({name:1})

Then create two indexes of name and age at a time

db.test1.createIndex({'name':1,'age':1})

insert image description here
When dealing with massive data, using compound indexes under certain rules can greatly improve query performance. The details are more complicated and will not be explained in detail here.


Guess you like

Origin blog.csdn.net/weixin_48964486/article/details/123643518