程序员人生 网站导航

MongoDB: 4. Index

栏目:综合技术时间:2014-06-10 18:55:02
MongoDB 提供了多样性的索引支持。

> for (var i = 0; i < 30; i++) {
... u = { name : "user" + i,
... age : 20 + i,
... contact : {
... address : ["address1_" + i, "address2_" + i],
... postcode : 100000 + i,
... }
... };
... db.users.insert(u);
... }
索引信息被保存在 system.indexes 中,且默认总是为 _id 创建索引。

> show collections
system.indexes
users

> db.system.indexes.find()
{ "name" : "_id_", "ns" : "blog.users", "key" : { "_id" : 1 } }
1. ensureIndex / dropIndex / reIndex

使用 ensureIndex 创建索引,dropIndex() 删除索引,dropIndexes() 删除全部索引(不包括 _id 等系统索引)。

> db.users.ensureIndex({name:1})
> db.users.ensureIndex({age:1})

> db.system.indexes.find()
{ "name" : "_id_", "ns" : "blog.users", "key" : { "_id" : 1 } }
{ "_id" : ObjectId("4c4a...b798"), "ns" : "blog.users", "key" : { "name" : 1 }, "name" : "name_1" }
{ "_id" : ObjectId("4c4a...b799"), "ns" : "blog.users", "key" : { "age" : 1 }, "name" : "age_1" }

> db.users.dropIndex({age:1})
{ "nIndexesWas" : 3, "ok" : true }

> db.users.dropIndexes()
{
"nIndexesWas" : 2,
"msg" : "non-_id indexes dropped for collection",
"ok" : true
}

> db.system.indexes.find()
{ "name" : "_id_", "ns" : "blog.users", "key" : { "_id" : 1 } }
reIndex 则是重建索引。

> db.users.ensureIndex({name:1})
> db.users.ensureIndex({age:1})

> db.system.indexes.find()
{ "name" : "_id_", "ns" : "blog.users", "key" : { "_id" : 1 } }
{ "_id" : ObjectId("4c4a...b82a"), "ns" : "blog.users", "key" : { "name" : 1 }, "name" : "name_1" }
{ "_id" : ObjectId("4c4a...b82b"), "ns" : "blog.users", "key" : { "age" : 1 }, "name" : "age_1" }

> db.users.reIndex()
{
"nIndexesWas" : 3,
"msg" : "indexes dropped for collection",
"ok" : 1,
"nIndexes" : 3,
"indexes" : [
{
"name" : "_id_",
"ns" : "blog.users",
"key" : {
"_id" : 1
}
},
{
"_id" : ObjectId("4c4a...b82a"),
"ns" : "blog.users",
"key" : {
"name" : 1
},
"name" : "name_1"
},
{
"_id" : ObjectId("4c4a...b82b"),
"ns" : "blog.users",
"key" : {
"age" : 1
},
"name" : "age_1"
}
],
"ok" : 1
}
当系统已有大量数据时,创建索引就是个非常耗时的活,我们可以在后台执行。

> db.users.dropIndexes()
{
"nIndexesWas" : 3,
"msg" : "non-_id indexes dropped for collection",
"ok" : true
}

> db.users.ensureIndex({name:1}, {backgroud:true})

> db.users.reIndex({backgroud:true})
{
"nIndexesWas" : 2,
"msg" : "indexes dropped for collection",
"ok" : 1,
"nIndexes" : 2,
"indexes" : [
{
"name" : "_id_",
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐