您的位置:首页 > 数据库 > Mongodb

MONGODB(二)——索引操作

2015-12-31 13:49 543 查看
一、
1、插入10w条数据
> for(var i = 0;i<100000;i++){
... var rand = parseInt(i*Math.random());
... db.person.insert({"name":"hxc"+i,"age":i})
... }
2、使用性能分析函数explain
> db.person.find({“name”:”hxc”+1000}).explain()
{
“cursor” : “BasicCursor”, //表扫描,也就是顺序查找
“isMultiKey” : false,
“n” : 1, //返回了一个文档
“nscannedObjects” : 100006, //浏览的文档数
“nscanned” : 100006,
“millis” : 58, //总共耗时58毫秒
}
3、建立索引
> db.person.ensureIndex({“name”:1})
> db.person.find({“name”:”hxc”+1000}).explain()
{
“cursor” : “BtreeCursor name_1″,采用B树结构存储索引,索引名为”name_1″
“isMultiKey” : false,
“n” : 1,
“nscannedObjects” : 1,
“nscanned” : 1, //!!!!
“nscannedObjectsAllPlans” : 1,
“nscannedAllPlans” : 1,
“nChunkSkips” : 0,
“millis” : 0, //!!!!
}

二、
1、唯一索引
建立唯一索引,重复键值不能输入。唯一索引也不能再已经存在重复键值的表上创建
db.person.ensureIndex({“name”:1},{“unique”:true})。
2、组合索引
> db.person.ensureIndex({“name”:1,”birthday”:1})
> db.person.ensureIndex({“birthday”:1,”name”:1})
查看生成的索引> db.person.getIndexes()
{
“v” : 1,
“key” : {
“name” : 1,
“birthday” : 1
},
“ns” : “test.person”,
“name” : “name_1_birthday_1″
},
{
“v” : 1,
“key” : {
“birthday” : 1,
“name” : 1
},
“ns” : “test.person”,
“name” : “birthday_1_name_1″
}
3、删除索引
> db.person.dropIndexes(“name_1″)
{
“nIndexesWas” : 4,
“msg” : “non-_id indexes dropped for collection”,
“ok” : 1
}

参考

[1] 《8天学通MongoDB》 http://www.cnblogs.com/huangxincheng/archive/2012/02/18/2356595.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: