第37章 MongoDB 高级索引教程
考虑以下文档集合(users ):
{
"address": {
"city": "Los Angeles",
"state": "California",
"pincode": "123"
},
"tags": [
"music",
"cricket",
"blogs"
],
"name": "Tom Benzamin"
}
以上文档包含了 address 子文档和 tags 数组。
索引数组字段
假设咱们基于标签来检索用户,为此咱们需要对集合中的数组 tags 建立索引。
在数组中创建索引,需要对数组中的每个字段依次建立索引。所以在咱们为数组 tags 创建索引时,会为 music、cricket、blogs三个值建立单独的索引。
使用以下命令创建数组索引:
>db.users.ensureIndex({"tags":1})
创建索引后,咱们可以这样检索集合的 tags 字段:
>db.users.find({tags:"cricket"})
为了验证咱们使用使用了索引,可以使用 explain 命令:
>db.users.find({tags:"cricket"}).explain()
以上命令执行结果中会显示 “cursor” : “BtreeCursor tags_1” ,则表示已经使用了索引。
索引子文档字段
假设咱们需要通过city、state、pincode字段来检索文档,由于这些字段是子文档的字段,所以咱们需要对子文档建立索引。
为子文档的三个字段创建索引,命令如下:
>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})
一旦创建索引,咱们可以使用子文档的字段来检索数据:
>db.users.find({"address.city":"Los Angeles"})
查询表达不一定遵循指定的索引的顺序,mongodb 会自动优化。所以上面创建的索引将支持以下查询:
>db.users.find({"address.state":"California","address.city":"Los Angeles"})
同样支持以下查询:
>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})
本专栏所有文章
第1章 MongoDB 教程 | 第2章 NoSQL 简介教程 |
---|---|
第3章 MongoDB 简介教程 | 第4章 Windows MongoDB教程 |
第5章 Linux MongoDB教程 | 第6章 OSX MongoDB教程 |
第7章 MongoDB 概念解析教程 | 第8章 MongoDB 连接教程 |
第9章 MongoDB 创建数据库教程 | 第10章 MongoDB 删除数据库教程 |
第11章 MongoDB 创建集合教程 | 第12章 MongoDB 删除集合教程 |
第13章 MongoDB 插入文档教程 | 第14章 MongoDB 更新文档教程 |
第15章 MongoDB 删除文档教程 | 第16章 MongoDB 查询文档教程 |
第17章 MongoDB 条件操作符教程 | 第18章 MongoDB $type 操作符教程 |
第19章 MongoDB Limit与Skip方法教程 | 第20章 MongoDB 排序教程 |
第21章 MongoDB 索引教程 | 第22章 MongoDB 聚合教程 |
第23章 MongoDB 复制(副本集)教程 | 第24章 MongoDB 分片教程 |
第25章 MongoDB 备份与恢复教程 | 第26章 MongoDB 监控教程 |
第27章 MongoDB Java教程 | 第28章 MongoDB PHP 扩展教程 |
第29章 MongoDB PHP教程 | 第30章 MongoDB PHP7教程 |
第31章 Node.js MongoDB教程 | 第32章 MongoDB 关系教程 |
第33章 MongoDB 数据库引用教程 | 第34章 MongoDB 覆盖索引查询教程 |
第35章 MongoDB 查询分析教程 | 第36章 MongoDB 原子操作教程 |
第37章 第37章 MongoDB 高级索引教程教程 | 第38章 MongoDB 索引限制教程 |
第39章 MongoDB ObjectId教程 | 第40章 MongoDB Map Reduce教程 |
第41章 MongoDB 全文检索教程 | 第42章 MongoDB 正则表达式教程 |
第43章 MongoDB 管理工具教程 | 第44章 MongoDB GridFS教程 |
第45章 MongoDB 固定集合教程 | 第46章 MongoDB 自动增长教程 |
寄语
本文有榴莲酱CSDN原创,欢迎点赞、转载,博客地址:https://blog.csdn.net/qq441540598
- 今天的努力工作,换来明天的美好生活。好好工作,开心生活。
- 所谓的永远,只是自卑的借口,强者不会选择等待。因为永远究竟是多远,谁也算不准。
- 女人,一定要努力的学会改变,学会挣钱,不然连发脾气的资格都没有。
- 记住吧:只有一个时间是重要的,那就是现在。它所以重要,就是因为它是我们有所作为的时间。
- 我到处采蜜,为的是要使“音乐”这座蜂房的味道更好、更甜。要知道这是人民的事业。