MongoDB索引
查看索引
1 .查看一个集合有哪些索引
> db.table.getIndexKeys()
> db.c2.getIndexKeys()
[ { "_id" : 1 } ]
2 .索引详情
> db.c2.getIndexes()
3 .查看集合的相关信息 【索引、大小等】
> db.c2.stats()
创建索引
普通索引语法:
> db.table.ensureIndex({key:1})
1 .将c2 集合的 name 字段添加索引
> db.c2.ensureIndex({name:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
创建唯一索引语法:
> db.table.ensureIndex({key:1},{unique:1})
1 .将name字段创建唯一索引 unique:1
> db.c2.ensureIndex({name:1},{unique:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
2 .查看唯一索引 "unique" : true
> db.c2.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "c2.c2"
},
{
"v" : 2,
"unique" : true,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "c2.c2"
}
]
删除索引
> db.c2.dropIndex({name:1})
{ "nIndexesWas" : 2, "ok" : 1 }