search
HomeDatabaseMongoDBLet's talk to you about the rich index types in MongoDB

This article will take you to understand MongoDB and introduce the rich index types in MongoDB. I hope it will be helpful to everyone! The functions of

Let's talk to you about the rich index types in MongoDB

MongoDB's index and MySql's index are basically similar in function and optimization principles, MySqlIndex types can basically be distinguished as:

  • Single key index - joint index
  • Primary key index (clustered index) -Non-primary key index (non-clustered index)

In addition to these basic classifications in MongoDB, there are also some special index types, such as: array index | sparse index | geospatial index | TTL index, etc.

For the convenience of testing below, we use the script to insert the following data

for(var i = 0;i < 100000;i++){
    db.users.insertOne({
        username: "user"+i,
        age: Math.random() * 100,
        sex: i % 2,
        phone: 18468150001+i
    });
}

Single key index

Single key index means that there is only one indexed field, which is the most basic index. Method.

Use the username field in the collection to create a single key index. MongoDB will automatically name this index username_1

db.users.createIndex({username:1})
&#39;username_1&#39;

After creating the index, check the query plan using the username field. stage is IXSCAN, which means index scanning is used

db.users.find({username:"user40001"}).explain()
{ 
   queryPlanner: 
   { 
     winningPlan: 
     { 
        ......
        stage: &#39;FETCH&#39;,
        inputStage: 
        { 
           stage: &#39;IXSCAN&#39;,
           keyPattern: { username: 1 },
           indexName: &#39;username_1&#39;,
           ......
        } 
     }
     rejectedPlans: [] ,
   },
   ......
   ok: 1 
}

Among the principles of index optimization, a very important principle is that the index should be built on a field with a high cardinality. The so-called cardinality is the number of non-repeating values ​​in a field, that is, when we create users If the age value that appears during collection is 0-99, then the age field will have 100 unique values, that is, the base of the age field is 100. The sex field will only have the two values ​​0 | 1, that is, the base of the sex field is 2, which is a fairly low base. In this case, the index efficiency is not high and will lead to index failure.

Let's build a sex field index to query the execution plan. You will find that the query is done Full table scan without related index.

db.users.createIndex({sex:1})
&#39;sex_1&#39;

db.users.find({sex:1}).explain()
{ 
  queryPlanner: 
  { 
     ......
     winningPlan: 
     { 
        stage: &#39;COLLSCAN&#39;,
        filter: { sex: { &#39;$eq&#39;: 1 } },
        direction: &#39;forward&#39; 
     },
     rejectedPlans: [] 
  },
  ......
  ok: 1 
}

Joint index

Joint index means there will be multiple fields on the index. Use age## below. # and sex create an index with two fields

db.users.createIndex({age:1,sex:1})
&#39;age_1_sex_1&#39;

Then we use these two fields to conduct a query, check the execution plan, and successfully go through this index

db.users.find({age:23,sex:1}).explain()
{ 
  queryPlanner: 
  { 
     ......
     winningPlan: 
     { 
        stage: &#39;FETCH&#39;,
        inputStage: 
        { 
           stage: &#39;IXSCAN&#39;,
           keyPattern: { age: 1, sex: 1 },
           indexName: &#39;age_1_sex_1&#39;,
           .......
           indexBounds: { age: [ &#39;[23, 23]&#39; ], sex: [ &#39;[1, 1]&#39; ] } 
        } 
     },
     rejectedPlans: [], 
  },
  ......
  ok: 1 
 }

Array index

Array index is to create an index on the array field, also called a multi-valued index. In order to test, the data in the

users collection will be added to some array fields below.

db.users.updateOne({username:"user1"},{$set:{hobby:["唱歌","篮球","rap"]}})
......

Create an array index and view its execution plan. Note that

isMultiKey: true means that the index used is a multi-valued index.

db.users.createIndex({hobby:1})
&#39;hobby_1&#39;

db.users.find({hobby:{$elemMatch:{$eq:"钓鱼"}}}).explain()
{ 
   queryPlanner: 
   { 
     ......
     winningPlan: 
     { 
        stage: &#39;FETCH&#39;,
        filter: { hobby: { &#39;$elemMatch&#39;: { &#39;$eq&#39;: &#39;钓鱼&#39; } } },
        inputStage: 
        { 
           stage: &#39;IXSCAN&#39;,
           keyPattern: { hobby: 1 },
           indexName: &#39;hobby_1&#39;,
           isMultiKey: true,
           multiKeyPaths: { hobby: [ &#39;hobby&#39; ] },
           ......
           indexBounds: { hobby: [ &#39;["钓鱼", "钓鱼"]&#39; ] } } 
         },
     rejectedPlans: [] 
  },
  ......
  ok: 1 
}

Array index is compared to other indexes Generally speaking, the index entries and volume must increase exponentially. For example, the average

size of the hobby array of each document is 10, then the hobby array index of this collection is The number of entries will be 10 times that of the ordinary index.

Joint array index

A joint array index is a joint index containing array fields. This type of index does not support one index. Contains multiple array fields, that is, there can be at most one array field in an index. This is to avoid the explosive growth of index entries. Suppose there are two array fields in an index, then the number of index entries will be n* of a normal index. m times

Geographic spatial index

Add some geographical information to the original

users collection

for(var i = 0;i < 100000;i++){
    db.users.updateOne(
    {username:"user"+i},
    {
        $set:{
            location:{
                type: "Point",
                coordinates: [100+Math.random() * 4,40+Math.random() * 3]
            }
        }
    });
}

Create a second Dimensional spatial index

db.users.createIndex({location:"2dsphere"})
&#39;location_2dsphere&#39;

//查询500米内的人
db.users.find({
  location:{
    $near:{
      $geometry:{type:"Point",coordinates:[102,41.5]},
      $maxDistance:500
    }
  }
})

The

type of the geographical spatial index has many containing Ponit(point) | LineString(line) | Polygon (Polygon)etc

TTL index

The full spelling of TTL is

time to live, which is mainly used for automatic deletion of expired data , to use this kind of index, you need to declare a time type field in the document, and then when creating a TTL index for this field, you also need to set an expireAfterSecondsThe expiration time unit is seconds, after the creation is completedMongoDBThe data in the collection will be checked regularly. When it appears:

##Current timeTT LIndex field time>expi reAfterSrcondsCurrent time - TTL index field time> expireAfterSrconds

The above is the detailed content of Let's talk to you about the rich index types in MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
MongoDB's Purpose: Flexible Data Storage and ManagementMongoDB's Purpose: Flexible Data Storage and ManagementMay 09, 2025 am 12:20 AM

MongoDB's flexibility is reflected in: 1) able to store data in any structure, 2) use BSON format, and 3) support complex query and aggregation operations. This flexibility makes it perform well when dealing with variable data structures and is a powerful tool for modern application development.

MongoDB vs. Oracle: Licensing, Features, and BenefitsMongoDB vs. Oracle: Licensing, Features, and BenefitsMay 08, 2025 am 12:18 AM

MongoDB is suitable for processing large-scale unstructured data and adopts an open source license; Oracle is suitable for complex commercial transactions and adopts a commercial license. 1.MongoDB provides flexible document models and scalability across the board, suitable for big data processing. 2. Oracle provides powerful ACID transaction support and enterprise-level capabilities, suitable for complex analytical workloads. Data type, budget and technical resources need to be considered when choosing.

MongoDB vs. Oracle: Exploring NoSQL and Relational ApproachesMongoDB vs. Oracle: Exploring NoSQL and Relational ApproachesMay 07, 2025 am 12:02 AM

In different application scenarios, choosing MongoDB or Oracle depends on specific needs: 1) If you need to process a large amount of unstructured data and do not have high requirements for data consistency, choose MongoDB; 2) If you need strict data consistency and complex queries, choose Oracle.

The Truth About MongoDB's Current SituationThe Truth About MongoDB's Current SituationMay 06, 2025 am 12:10 AM

MongoDB's current performance depends on the specific usage scenario and requirements. 1) In e-commerce platforms, MongoDB is suitable for storing product information and user data, but may face consistency problems when processing orders. 2) In the content management system, MongoDB is convenient for storing articles and comments, but it requires sharding technology when processing large amounts of data.

MongoDB vs. Oracle: Document Databases vs. Relational DatabasesMongoDB vs. Oracle: Document Databases vs. Relational DatabasesMay 05, 2025 am 12:04 AM

Introduction In the modern world of data management, choosing the right database system is crucial for any project. We often face a choice: should we choose a document-based database like MongoDB, or a relational database like Oracle? Today I will take you into the depth of the differences between MongoDB and Oracle, help you understand their pros and cons, and share my experience using them in real projects. This article will take you to start with basic knowledge and gradually deepen the core features, usage scenarios and performance performance of these two types of databases. Whether you are a new data manager or an experienced database administrator, after reading this article, you will be on how to choose and use MongoDB or Ora in your project

What's Happening with MongoDB? Exploring the FactsWhat's Happening with MongoDB? Exploring the FactsMay 04, 2025 am 12:15 AM

MongoDB is still a powerful database solution. 1) It is known for its flexibility and scalability and is suitable for storing complex data structures. 2) Through reasonable indexing and query optimization, its performance can be improved. 3) Using aggregation framework and sharding technology, MongoDB applications can be further optimized and extended.

Is MongoDB Doomed? Dispelling the MythsIs MongoDB Doomed? Dispelling the MythsMay 03, 2025 am 12:06 AM

MongoDB is not destined to decline. 1) Its advantage lies in its flexibility and scalability, which is suitable for processing complex data structures and large-scale data. 2) Disadvantages include high memory usage and late introduction of ACID transaction support. 3) Despite doubts about performance and transaction support, MongoDB is still a powerful database solution driven by technological improvements and market demand.

The Future of MongoDB: A Look at its ProspectsThe Future of MongoDB: A Look at its ProspectsMay 02, 2025 am 12:08 AM

MongoDB'sfutureispromisingwithgrowthincloudintegration,real-timedataprocessing,andAI/MLapplications,thoughitfaceschallengesincompetition,performance,security,andeaseofuse.1)CloudintegrationviaMongoDBAtlaswillseeenhancementslikeserverlessinstancesandm

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version