Let's talk to you about the rich index types in MongoDB
Feb 17, 2022 am 10:58 AMThis 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
MongoDB
's index and MySql
's index are basically similar in function and optimization principles, MySql
Index 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}) 'username_1'
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: 'FETCH', inputStage: { stage: 'IXSCAN', keyPattern: { username: 1 }, indexName: 'username_1', ...... } } 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}) 'sex_1' db.users.find({sex:1}).explain() { queryPlanner: { ...... winningPlan: { stage: 'COLLSCAN', filter: { sex: { '$eq': 1 } }, direction: 'forward' }, 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}) 'age_1_sex_1'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: 'FETCH', inputStage: { stage: 'IXSCAN', keyPattern: { age: 1, sex: 1 }, indexName: 'age_1_sex_1', ....... indexBounds: { age: [ '[23, 23]' ], sex: [ '[1, 1]' ] } } }, 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 theusers 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}) 'hobby_1' db.users.find({hobby:{$elemMatch:{$eq:"釣魚"}}}).explain() { queryPlanner: { ...... winningPlan: { stage: 'FETCH', filter: { hobby: { '$elemMatch': { '$eq': '釣魚' } } }, inputStage: { stage: 'IXSCAN', keyPattern: { hobby: 1 }, indexName: 'hobby_1', isMultiKey: true, multiKeyPaths: { hobby: [ 'hobby' ] }, ...... indexBounds: { hobby: [ '["釣魚", "釣魚"]' ] } } }, 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 timesGeographic spatial index
Add some geographical information to the originalusers 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"}) 'location_2dsphere' //查詢500米內(nèi)的人 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 istime 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 completed
MongoDBThe data in the collection will be checked regularly. When it appears:

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

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 is suitable for unstructured data and high scalability requirements, while Oracle is suitable for scenarios that require strict data consistency. 1.MongoDB flexibly stores data in different structures, suitable for social media and the Internet of Things. 2. Oracle structured data model ensures data integrity and is suitable for financial transactions. 3.MongoDB scales horizontally through shards, and Oracle scales vertically through RAC. 4.MongoDB has low maintenance costs, while Oracle has high maintenance costs but is fully supported.

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.

To start the MongoDB server: On a Unix system, run the mongod command. On Windows, run the mongod.exe command. Optional: Set the configuration using the --dbpath, --port, --auth, or --replSet options. Use the mongo command to verify that the connection is successful.

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512
