MongoDB的简单实用例子。

_id的结构:Time + Machine + PID + INC

MongoDB的索引原理采用B-Tree,MySQL采用B+Tree,详细下面会谈到。这里先从应用角度谈起。

索引的相关理论参看数据库理论基础。大部分MySQL/SQLite中的索引都适用于MongoDB。所以这部分重点在使用MongoDB创建索引上,而不是如何选择字段创建索引。索引优化上有一个问题,在多键索引中,通常把基数较大的键放到索引的前面。

尽管索引提升查询速度,但某些情况下不适合索引:

  1. 集合较小
  2. 文档较小
  3. 非选择性查询

MongoDB在不使用索引的查询时全表扫描查询。例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (i=0; i<100000; i++) {
db.test.insert(
{
"index": i,
"name": "allen:" + i,
"age": Math.floor(Math.random()*10*i),
"created": new Date()
}
);
}

//查看该查询过程

db.test.find({"name": "allen:65536"}).explain()

创建索引:

db.test.ensureIndex({“name”: 1})
指定”name”字段创建索引。

创建符合索引(compound index):

db.test.ensureIndex({“name”: 1, “age”: 1})
会根据name先排序然后再根据age排序。

如果要强制使用索引:

db.test.find({“index”: 1234, “age”: 66}).hint({“name”: 1, “age”: 1})

指定复合索引通常采用如下形式:

db.test.ensureIndex({“sortKey”: 1, “queryCriteria”: 1})
排序键先,查询键后

复合索引中指定键的方向:

db.test.ensureIndex({“age”: 1, “name”: -1})
db.test.ensureIndex({“age”: -1, “name”: 1})
它们本质上是一样的

索引对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"index": i,
"name": "allen:" + i,
"age": Math.floor(Math.random()*10*i),
"created": new Date()
"love": {
"books": ["algorithm", "OS", "Linux"],
"food": "fruits",
"sleep": false
}
}

//那么所food索引如下
db.test.ensureIndex({"love.food": 1})

索引数组:
对数组索引实际上是对数组的每个元素索引,但该索引并不包含任何位置信息,所以数组索引并不能优化通过数组下标查找元素的查询。

db.test.ensureIndex({“love.books”: 1})

针对指定条目的索引

db.test.ensureIndex({“love.books.5”: 1})

索引类型

和MySQL不同,MongoDB采用的是B-Tree索引。为什么MySQL使用B+Tree而MongoDB使用B-Tree呢?这一部分将在索引机制上讲到。

参考:《MongoDB权威指南》

转载请包括本文地址:https://allenwind.github.io/blog/1698/
更多文章请参考:https://allenwind.github.io/blog/archives/