上图展示了有索引和无索引的查询方式,目测都可以看出效率。
# 查询articles集合的索引
db.articles.getIndexes();
# 添加titlei字段索引,并且为升序
db.articles.ensureIndex({title:1});
#重构索引(慎用)
db.articles.reIndex();
注意:索引排序规则升序:1,降序-1
Single Field (单字段索引) mongodb允许定义单个字段的索引,与default _id一样,只是字段不同。
Compound Index (复合索引[多字段索引])
mongodb中可以自定多个字段的索引。例如,如果一个复合指标包括{userid:1,score:-1 }
,索引排序第一的用户名后,在每一个用户标识符值,按得分++倒序++排序。
{
"_id": ObjectId(...),
"item": "Banana",
"category": ["food", "produce", "grocery"],
"location": "4th Street Store",
"stock": 4,
"type": "cases",
"arrival": Date(...)
}
创建方法:
# 创建item、stock字段的复合索引,并且升序排序
db.products.ensureIndex( { "item": 1, "stock": 1 } )
注意:Hashed 字段不能创建索引,如果创建将出现错误
Application Sort Order 使用案例:降序用户名升序时间。
# 查询结果集中排序
db.events.find().sort( { username: -1, date: 1 } )
# 查询结果集中排序
db.user_scores.find().sort({score:-1,date:-1}).limit(1)
# 执行相关查询可以看出查询效率大大提高
{
userid:"marker",
address:[
{zip:"618255"},
{zip:"618254"}
]
}
# 创建索引,并将zip升序排列
db.users.ensureIndex({"address.zip": 1});
# 假如我们做这样的查询
db.users.find({"addr":{"$in":[{zip:"618254"}]}})
注意:你可以创建 多键复合索引(multikey compound indexes)
Geospatial Index (地理空间索引)
db.places.ensureIndex( { loc : "2dsphere" } )
$text
做查询操作。
2.6版本 默认情况下使文本搜索功能。在MongoDB 2.4,你需要使文本搜索功能手动创建全文索引和执行文本搜索
# 创建文本索引 (2.6你就不用这么麻烦了哦)
db.articles.ensureIndex({content:"text"});
复合索引可以包含文本索引 称为:复合文本索引(compound text indexes),但有限制
1. 复合文本索引不能包含任何其他特殊索引类型,比如:多键索引(multi-key Indexes)
2. 如果复合文本索引包含文本索引的键,执行$text查询必须相同查询条件。可能翻译不对原文:
(If the compound text index includes keys preceding the text index key, to perform a $text search, the query
predicate must include equality match conditions on the preceding keys1)
# 给user_scores的score字段创建一个哈希索引
db.user_scores.ensureIndex( { score: "hashed" } )
1. 不支持复合索引
2. 必须是date时间类型字段
3. 如果是date数组,按照最早时间过期。
TTL index不保证过期时间立即删除,
后台任务没60秒运行删除,
依赖于mongod进程Unique Indexes
# 创建唯一索引
db.members.ensureIndex( { "user_id": 1 }, { unique: true } )
注意:如果字段为null,那么就以null值,但不能重复插入空值。如果collection中有两个实体唯一索引字段为空,则不能创建唯一索引
也就是说,我们还可以利用它作为类似于关系型数据库的唯一约束。
# 强制插入空值对象后报错
> db.users.insert({content:"unique testing"})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicat
e key error index: test.users.$dsadsadsa dup key: { : null }"
}
})
db.addresses.ensureIndex( { "xmpp_id": 1 }, { sparse: true } )
db.addresses.ensureIndex( { "xmpp_id": 1 }, {background: true } )
我们知道如果哦阻塞所有请求,建立索引就会很快,但是使用系统的用户就需要等待,影响了数据库的操作,因此可以更具具体情况来选择使用background属性# 自动生成索引名称
db.products.ensureIndex( { item: 1, quantity: -1 } )
# 被命名为: item_1_quantity_-1
# 自定义索引名称
db.products.ensureIndex( { item: 1, quantity: -1 } , { name: "inventory" } )
在2.6版本中更新的,这块没有深入了解。
# 添加/修改索引
db.users.ensureIndex({name:"text"});
# 删除集合所有索引
db.users.dropIndexes();
# 删除特定索引 (删除id字段升序的索引)
db.users.dropIndex({"id":1})
# 获取集合索引
db.users.getIndexes();
# 重构索引
db.users.reIndex();
声明:本人英文水平有限,部分翻译或者理解错误请谅解。也可以偷偷告诉我,更新该文章!