当前位置:Gxlcms > 数据库问题 > Mongodb索引

Mongodb索引

时间:2021-07-01 10:21:17 帮助过:22人阅读

  • > 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"
  •    }
  • ]
  • >
  •  

    创建索引

     

    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索引

    标签:was   before   uil   mat   nbsp   create   creat   address   created   

    人气教程排行