首页 > 代码库 > Mongodb索引
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索引
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。