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 vs. Oracle: Understanding Key DifferencesMongoDB vs. Oracle: Understanding Key DifferencesApr 16, 2025 am 12:01 AM

MongoDB is suitable for handling large-scale unstructured data, and Oracle is suitable for enterprise-level applications that require transaction consistency. 1.MongoDB provides flexibility and high performance, suitable for processing user behavior data. 2. Oracle is known for its stability and powerful functions and is suitable for financial systems. 3.MongoDB uses document models, and Oracle uses relational models. 4.MongoDB is suitable for social media applications, while Oracle is suitable for enterprise-level applications.

MongoDB: Scaling and Performance ConsiderationsMongoDB: Scaling and Performance ConsiderationsApr 15, 2025 am 12:02 AM

MongoDB's scalability and performance considerations include horizontal scaling, vertical scaling, and performance optimization. 1. Horizontal expansion is achieved through sharding technology to improve system capacity. 2. Vertical expansion improves performance by increasing hardware resources. 3. Performance optimization is achieved through rational design of indexes and optimized query strategies.

The Power of MongoDB: Data Management in the Modern EraThe Power of MongoDB: Data Management in the Modern EraApr 13, 2025 am 12:04 AM

MongoDB is a NoSQL database because of its flexibility and scalability are very important in modern data management. It uses document storage, is suitable for processing large-scale, variable data, and provides powerful query and indexing capabilities.

How to delete mongodb in batchesHow to delete mongodb in batchesApr 12, 2025 am 09:27 AM

You can use the following methods to delete documents in MongoDB: 1. The $in operator specifies the list of documents to be deleted; 2. The regular expression matches documents that meet the criteria; 3. The $exists operator deletes documents with the specified fields; 4. The find() and remove() methods first get and then delete the document. Please note that these operations cannot use transactions and may delete all matching documents, so be careful when using them.

How to set mongodb commandHow to set mongodb commandApr 12, 2025 am 09:24 AM

To set up a MongoDB database, you can use the command line (use and db.createCollection()) or the mongo shell (mongo, use and db.createCollection()). Other setting options include viewing database (show dbs), viewing collections (show collections), deleting database (db.dropDatabase()), deleting collections (db.&lt;collection_name&gt;.drop()), inserting documents (db.&lt;collecti

How to deploy a mongodb clusterHow to deploy a mongodb clusterApr 12, 2025 am 09:21 AM

Deploying a MongoDB cluster is divided into five steps: deploying the primary node, deploying the secondary node, adding the secondary node, configuring replication, and verifying the cluster. Including installing MongoDB software, creating data directories, starting MongoDB instances, initializing replication sets, adding secondary nodes, enabling replica set features, configuring voting rights, and verifying cluster status and data replication.

How to use mongodb application scenarioHow to use mongodb application scenarioApr 12, 2025 am 09:18 AM

MongoDB is widely used in the following scenarios: Document storage: manages structured and unstructured data such as user information, content, product catalogs, etc. Real-time analysis: Quickly query and analyze real-time data such as logs, monitoring dashboard displays, etc. Social Media: Manage user relationship maps, activity streams, and messaging. Internet of Things: Process massive time series data such as device monitoring, data collection and remote management. Mobile applications: As a backend database, synchronize mobile device data, provide offline storage, etc. Other areas: diversified scenarios such as e-commerce, healthcare, financial services and game development.

How to view the mongodb versionHow to view the mongodb versionApr 12, 2025 am 09:15 AM

How to view MongoDB version: Command line: Use the db.version() command. Programming language driver: Python: print(client.server_info()["version"])Node.js: db.command({ version: 1 }, (err, result) => { console.log(result.version); });

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor