💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
一、创建索引 MongoDB提供了对文档集合中任何字段进行索引,默认情况下在_id字段进行索引。 * 单键索引 ,在单个字段上创建升序索引 ~~~ > db.records.find() { "_id" : ObjectId("5a97ceafc1670638c95ceb9c"), "score" : 1034, "location" : { "state" : "NY", "city" : "shanghai" } } > db.records.createIndex({score:1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 3, "numIndexesAfter" : 3, "note" : "all indexes already exist", "ok" : 1 } 说明: 1)1表示按升序,-1表示按降序 2)在该字段上创建了索引,就支持通过该字段加速查询 3)background:true,表示后台构建索引 4)unique:true 唯一索引 > db.records.find({score:{"$gt":1020}}) { "_id" : ObjectId("5a97ceafc1670638c95ceb9c"), "score" : 1034, "location" : { "state" : "NY", "city" : "shanghai" } } ~~~ * 多键索引 ~~~ > db.records.createIndex({"location.state":1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 3, "numIndexesAfter" : 4, "ok" : 1 } ~~~ * 组合索引 格式: db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... } ) > db.products.createIndex({"item":1,"stock":1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } * 文本索引(text indexes) * hash索引(Hash indexes) 二、查看索引 1)db.people.getIndexes() > db.records.getIndexes() 三、删除索引 > db.records.dropIndex({"score":1}) { "nIndexesWas" : 4, "ok" : 1 } 四:使用explain()返回查询计划 > db.foo.find({age:{"$gt":20}}).explain("executionStats") "executionStats" : { "executionSuccess" : true,-----是否执行成功 "nReturned" : 2,------查询返回的条数 "executionTimeMillis" : 1,------整体执行时间 "totalKeysExamined" : 2,-------索引扫描次数 "totalDocsExamined" : 2,-------文档扫描次数 管理索引 * 查看集合中索引在磁盘上的存储大小 > db.foo.stats().indexSizes { "_id_" : 36864, "age_1" : 16384 } 单位为byte * 查看各索引具体内存占用大小 > db.foo.stats({indexDetails:true}).indexDetails 索引状态 > db.foo.aggregate([{$indexStats:{}}]) { "name" : "age_1", "key" : { "age" : 1 }, "host" : "node1.51yuki.cn:27017", "ac cesses" : { "ops" : NumberLong(2), "since" : ISODate("2018-03-08T08:01:52.801Z") } } { "name" : "_id_", "key" : { "_id" : 1 }, "host" : "node1.51yuki.cn:27017", "acc esses" : { "ops" : NumberLong(0), "since" : ISODate("2018-03-01T06:48:40.845Z") NumberLong,索引调用次数