国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > MongoDB: 4. Index

MongoDB: 4. Index

来源:程序员人生   发布时间:2014-06-10 18:55:02 阅读次数:2873次
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_",
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生