首页 > 代码库 > Mongodb索引

Mongodb索引

查询索引

  1. 索引存放在system.indexes集合中
  2. > show tables
  3. address
  4. data
  5. person
  6. system.indexes
  7. 默认会为所有的ID建上索引 而且无法删除
  8. > db.system.indexes.find()
  9. { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.person" }
  10. { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.address" }
  11. { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.data" }
  12. 单独查询一个集合的索引
  13. > db.person.getIndexes();
  14. [
  15.    {
  16.       "v" : 1,
  17.       "key" : {
  18.          "_id" : 1
  19.       },
  20.       "name" : "_id_",
  21.       "ns" : "mydb.person"
  22.    }
  23. ]
  24. >

 

创建索引

 

  1. > db.person.find();
  2. { "_id" : ObjectId("593011c8a92497992cdfac10"), "name" : "xhj", "age" : 30, "address" : DBRef("address", ObjectId("59314b07e693aae7a5eb72ab")) }
  3. { "_id" : ObjectId("59301270a92497992cdfac11"), "name" : "zzj", "age" : 2 }
  4. { "_id" : ObjectId("593015fda92497992cdfac12"), "name" : "my second child", "age" : "i do not know" }
  5. { "_id" : ObjectId("592ffd872108e8e79ea902b0"), "name" : "zjf", "age" : 30, "address" : { "province" : "河南省", "city" : "南阳市", "building" : "桐柏县" } }
  6. 1升序 -1降序
  7. > db.person.ensureIndex({age:1});
  8. {
  9.    "createdCollectionAutomatically" : false,
  10.    "numIndexesBefore" : 1,
  11.    "numIndexesAfter" : 2,
  12.    "ok" : 1
  13. }
  14. 可以在集合上创建索引
  15. > db.person.ensureIndex({address:1});
  16. {
  17.    "createdCollectionAutomatically" : false,
  18.    "numIndexesBefore" : 2,
  19.    "numIndexesAfter" : 3,
  20.    "ok" : 1
  21. }
  22. 复合索引
  23. > db.person.ensureIndex({name:1,address:1});
  24. {
  25.    "createdCollectionAutomatically" : false,
  26.    "numIndexesBefore" : 3,
  27.    "numIndexesAfter" : 4,
  28.    "ok" : 1
  29. }
  30. 唯一索引:
  31. > db.person.ensureIndex({name:1},{unique:true});
  32. {
  33.    "createdCollectionAutomatically" : false,
  34.    "numIndexesBefore" : 4,
  35.    "numIndexesAfter" : 5,
  36.    "ok" : 1
  37. }

删除索引:

  1. 删除一个索引
  2. > db.person.dropIndex({name:1});
  3. { "nIndexesWas" : 5, "ok" : 1 }
  4. 删除所有索引
  5. > db.person.dropIndexes();
  6. {
  7.    "nIndexesWas" : 4,
  8.    "msg" : "non-_id indexes dropped for collection",
  9.    "ok" : 1
  10. }

 

Mongodb索引