Home Database Mysql Tutorial MongoDB初探-细说索引

MongoDB初探-细说索引

Jun 07, 2016 pm 03:29 PM
mongodb for optimization Preliminary exploration operate check index

一、索引操作 索引是为了优化查询速度而生,MongoDB的索引和其他关系型数据库,比如MySQL,Oracle等的索引几乎相同,对于它们的索引优化经验同样适用于MongoDB。 1、创建索引 MongoDB中建立索引是通过ensureIndex操作完成的。下面测试了在使用索引和不使用索

一、索引操作

索引是为了优化查询速度而生,MongoDB的索引和其他关系型数据库,比如MySQL,Oracle等的索引几乎相同,对于它们的索引优化经验同样适用于MongoDB。

1、创建索引

MongoDB中建立索引是通过ensureIndex操作完成的。下面测试了在使用索引和不使用索引下的性能差别,使用explain函数进行查询性能分析。

插入测试数据:

\

不使用索引的查询:喎?http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PGltZyBzcmM9"http://www.2cto.com/uploadfile/Collfiles/20140324/2014032409104154.jpg" alt="\">

使用索引的查询:

\

由以上测试可见,使用恰当的索引查找可以大大优化查询效率。

2、删除索引

\

索引的元信息存储在每个数据库的system.indexes集合中,该集合为保留集合,不能对其插入或删除文档。
操作只能通过ensureIndex或dropIndexes进行。

二、唯一索引

唯一索引可以确保集合的每一个文档的指定键都有唯一值。MongoDB建立唯一索引的方式如下:

db.person.ensureIndex({"name":1},{"unique":true})
Copy after login
\

如果没有对应的键,索引会将其作为null存储。所以,如果对某个键建立了唯一索引,但插入了多个缺少该索引键的文档,则由于文档包含null值而导致插入失败。

三、组合索引

通过为ensureIndex的第一个参数传入多个键值的文档来实现组合索引的建立。组合索引适用于对多条件查询的优化上,一般来说,如果索引包含N个键,则对于前几个键的查询都会有帮助。比如有个索引{"a":1,"b":1,"c":1,...,"z":1},实际上是有了{"a":1},{"a":1,"b":1},{"a":1,"b":1,"c":1}等的索引,但使用{"b":1},{"a":1,"c":1}等索引的查询则不会被优化。
\

四、地理空间索引

MongoDB的地理空间索引用于处理平面坐标的查询,对于查找离当前位置最近的N个场所非常适用,在LBS应用中经常使用。

1、创建空间索引

db.map.ensureIndex({"gps":"2d"})
Copy after login
"gps"键的值必须是某种形式的一对值:一个包含两个元素的数组或是包含两个键(键名随意)的内嵌文档,如下所示:
{"gps":[0,100]}
{"gps":{"x":0,"y":30}}
{"gps":{"latitude":0,"longitude":100}}
Copy after login
默认情况下,地理空间索引假设值的范围是-180~180,这对于处理经纬度非常方便,也可以设置其范围:
db.map.ensureIndex({"gps":"2d"},{"min":-360,"max":360})
Copy after login
2、查找

通过find函数查找:

将按照离坐标点(40,80)由近及远的方式将map集合的前5个文档返回。

db.map.find({"gps":{"$near":[40,80]}}).limit(5)
Copy after login

通过数据库命令查找:

db.runCommand({geoNear:"map",near:[40,80],num:5});
Copy after login
geoNear和使用$near的find普通查找类似,不过geoNear还会返回每个文档到查询点的距离。该距离以插入数据为单位,比如按照经纬度的角度插入,那距离就是经纬度。

具体其他空间索引的查找请参考MongoDB官方文档关于索引的介绍。

五、总结

对于索引的使用,要建立合适的索引,可以使用explain查看当前索引的效果。如果索引不适合当前业务需求的话,就要修改或删除,以免不必要或不恰当的索引对数据库操作产生影响。毕竟索引需要消耗内存和文件存储。对于索引要实时维护,不要索引每一个键。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

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:

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

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.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

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

How to choose a database for GitLab on CentOS How to choose a database for GitLab on CentOS Apr 14, 2025 pm 04:48 PM

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

How to set up users in mongodb How to set up users in mongodb Apr 12, 2025 am 08:51 AM

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.

See all articles