Mongodb索引
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongodb索引相关的知识,希望对你有一定的参考价值。
查询索引
- 索引存放在system.indexes集合中
- > show tables
- address
- data
- person
- system.indexes
- 默认会为所有的ID建上索引 而且无法删除
- > db.system.indexes.find()
- { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.person" }
- { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.address" }
- { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.data" }
- 单独查询一个集合的索引
- > db.person.getIndexes();
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "mydb.person"
- }
- ]
- >
创建索引
- > db.person.find();
- { "_id" : ObjectId("593011c8a92497992cdfac10"), "name" : "xhj", "age" : 30, "address" : DBRef("address", ObjectId("59314b07e693aae7a5eb72ab")) }
- { "_id" : ObjectId("59301270a92497992cdfac11"), "name" : "zzj", "age" : 2 }
- { "_id" : ObjectId("593015fda92497992cdfac12"), "name" : "my second child", "age" : "i do not know" }
- { "_id" : ObjectId("592ffd872108e8e79ea902b0"), "name" : "zjf", "age" : 30, "address" : { "province" : "河南省", "city" : "南阳市", "building" : "桐柏县" } }
- 1升序 -1降序
- > db.person.ensureIndex({age:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 1,
- "numIndexesAfter" : 2,
- "ok" : 1
- }
- 可以在集合上创建索引
- > db.person.ensureIndex({address:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 2,
- "numIndexesAfter" : 3,
- "ok" : 1
- }
- 复合索引
- > db.person.ensureIndex({name:1,address:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 3,
- "numIndexesAfter" : 4,
- "ok" : 1
- }
- 唯一索引:
- > db.person.ensureIndex({name:1},{unique:true});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 4,
- "numIndexesAfter" : 5,
- "ok" : 1
- }
删除索引:
- 删除一个索引
- > db.person.dropIndex({name:1});
- { "nIndexesWas" : 5, "ok" : 1 }
- 删除所有索引
- > db.person.dropIndexes();
- {
- "nIndexesWas" : 4,
- "msg" : "non-_id indexes dropped for collection",
- "ok" : 1
- }
以上是关于Mongodb索引的主要内容,如果未能解决你的问题,请参考以下文章