_id索引
_id 索引是绝大多数集合默认建立的索引,对于每个插入的数据,MongoDB 会自动生成一条唯一的 _id 字段。
12345678910111213141516 | > db.jerome_2.collection.insert({x:2}) WriteResult({ "nInserted" : 1 }) > db.jerome_2.collection.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_" , "ns" : "jerome.jerome_2.collection" } ] > db.jerome_2.collection.findOne() { "_id" : ObjectId( "557004f1f2824fa15224e20b" ), "x" : 2 } > |
单键索引
单键索引是最普通的索引,与_id 索引不同,单键索引不会自动创建。
1234567891011121314151617181920212223242526272829 | > db.jerome_2.collection.ensureIndex({x:1}) # 创建单键索引 { "createdCollectionAutomatically" : false , "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.jerome_2.collection.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_" , "ns" : "jerome.jerome_2.collection" }, { "v" : 1, "key" : { "x" : 1 }, "name" : "x_1" , "ns" : "jerome.jerome_2.collection" } ] > db.jerome_2.collection. find ({x:1}) #使用创建的索引查询 { "_id" : ObjectId( "557005a5f2824fa15224e20c" ), "x" : 1, "y" : 2, "z" : 3 } > |
多键索引
多键索引和单键索引创建形式相同,区别在于字段的值。 单键索引:值为一个单一的值,例如字符串,数字或者日期。 多键索引:值具有多个记录,例如数组。
123456789101112131415161718192021222324 | > db.jerome_2.collection.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_" , "ns" : "jerome.jerome_2.collection" }, { "v" : 1, "key" : { "x" : 1 }, "name" : "x_1" , "ns" : "jerome.jerome_2.collection" } ] > db.jerome_2.collection. find () { "_id" : ObjectId( "557004f1f2824fa15224e20b" ), "x" : 2 } { "_id" : ObjectId( "557005a5f2824fa15224e20c" ), "x" : 1, "y" : 2, "z" : 3 } > db.jeroem_2.collection.insert({x:[1,2,3,4,5]}) #插入一条数组数据,对于这条数据来讲,mongodb为其创建了一个多键索引 WriteResult({ "nInserted" : 1 }) |
复合索引
当我们的查询条件不只有一个时,就需要建立复合索引。
12345678910 | > db.jerome_2.collection.ensureIndex({x:1,y:1}) #创建 { "createdCollectionAutomatically" : false , "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 } > db.jerome_2.collection. find ({x:1,y:2}) #使用 { "_id" : ObjectId( "557005a5f2824fa15224e20c" ), "x" : 1, "y" : 2, "z" : 3 } > |
过期索引
过期索引是在一段时间后会过期的索引。在索引过期后,相应的数据会被删除。这适合存储一些在一段时间之后会失效的数据,比如用户的登陆信息、存储的日志等。
123456789101112131415161718192021 | > db.jerome_2.collection.ensureIndex({ time :1},{expireAfterSeconds:30}) #创建过期索引,过期时间30秒 { "createdCollectionAutomatically" : false , "numIndexesBefore" : 3, "numIndexesAfter" : 4, "ok" : 1 } > db.jerome_2.collection.insert({ time :new Date()}) #插入数据测试 WriteResult({ "nInserted" : 1 }) > db.jerome_2.collection. find () { "_id" : ObjectId( "557004f1f2824fa15224e20b" ), "x" : 2 } { "_id" : ObjectId( "557005a5f2824fa15224e20c"
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
|