0
点赞
收藏
分享

微信扫一扫

mongodb的索引

 

 在后台创建索引的原因:

        在前台创建索引期间会锁定数据库,会导致其它操作无法进行数据读写,在后台创建索引是,会定期释放写锁,从而保证其它操作的运行,但是后台操作会在耗时更长,尤其是在频繁进行写入的服务器上。

 

创建索引:

 

db.table_name.ensureIndex(keys[,options])

1, keys,要建立索引的参数列表。如:{KEY:1},其中key表示字段名,1表示升序排序,也可使用使用数字-1降序。

2, options,可选参数,表示建立索引的设置。可选值如下:

background,Boolean,在后台建立索引,以便建立索引时不阻止其他数据库活动。默认值 false。
unique,Boolean,创建唯一索引。默认值 false。
name,String,指定索引的名称。如果未指定,MongoDB会生成一个索引字段的名称和排序顺序串联。
dropDups,Boolean,创建唯一索引时,如果出现重复删除后续出现的相同索引,只保留第一个。
sparse,Boolean,对文档中不存在的字段数据不启用索引。默认值是 false。
v,index version,索引的版本号。
weights,document,索引权重值,数值在 1 到 99,999

 

#  在字段age 上创建索引,1(升序);-1(降序):

db.users.ensureIndex({age:1})

# _id 是创建表的时候自动创建的索引,此索引是不能够删除的。

# 当系统已有大量数据时,创建索引就是个非常耗时的活,我们可以在后台执行,只需指定“backgroud:true”即可。

db.t3.ensureIndex({age:1} , {backgroud:true})

 db.os_t_TaskReport_20210125.createIndex( { "groupId": 1,"strategyId":1,"crowdPackageId":1 },{"background":true} )

 

db.collection.ensureIndex( { "a": 1, "b": 1 }, { unique: true } )

db.collection.ensureIndex({"yourFieldName1":1,"yourFieldName2":1},{background: true} );

 

创建唯一索引:

//在userinfos的name字段添加唯一索引

db.userinfos.createIndex({name:1},{unique:true})

 

创建TTL索引:

TTL索引(TTL indexes)是一种特殊的单键索引,用于设置document的过期时间,mongoDB会在document过期后将其删除,TTL非常容易实现类似缓存过期策略的功能。我们看一个使用TTL索引的栗子:

复制代码
//添加测试数据
db.logs.insertMany([
{_id:1,createtime:new Date(),msg:"log1"},
{_id:2,createtime:new Date(),msg:"log2"},
{_id:3,createtime:new Date(),msg:"log3"},
{_id:4,createtime:new Date(),msg:"log4"}
])
//在createtime字段添加TTL索引,过期时间是120s
db.logs.createIndex({createtime:1}, { expireAfterSeconds: 120 })


//logs中的document在创建后的120s后过期,会被mongoDB自动删除

 注意:TTL索引只能设置在date类型字段(或者包含date类型的数组)上,过期时间为字段值+exprireAfterSeconds;document过期时不一定就会被立即删除,因为mongoDB执行删除任务的时间间隔是60s;capped Collection不能设置TTL索引,因为mongoDB不能主动删除capped Collection中的document。

 

 

 后台创建索引的方式,查看创建索引的进度:db.currentOp()

####################################################################

# 后台创建索引:

mivpn:PRIMARY> db.foo.ensureIndex({"age":1},{"background":true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1,
"operationTime" : Timestamp(1611734201, 1174),
"$clusterTime" : {
"clusterTime" : Timestamp(1611734201, 1174),
"signature" : {
"hash" : BinData(0,"piMYPCGQ7K+Jgb94d5bnwd+Sv10="),
"keyId" : NumberLong("6919692836459773955")
}
}
}

#############################################################################################

# 查看数据结构:

mivpn:PRIMARY> db.foo.find().limit(2).skip(100)
{ "_id" : ObjectId("6011183100011675ad68a8cc"), "idx" : 100, "name" : "user 1", "age" : 10 }
{ "_id" : ObjectId("6011183100011675ad68a8cd"), "idx" : 101, "name" : "user 1", "age" : 11 }
mivpn:PRIMARY>

#############################################################################################

# db.currentOp():查看索引创建进度:


{
"host" : "c3-dba-glc-db03.bj:28042",
"desc" : "conn3102",
"connectionId" : 3102,
"client" : "10.10.10.10:55873",
"appName" : "MongoDB Shell",
"clientMetadata" : {
"application" : {
"name" : "MongoDB Shell"
},
"driver" : {
"name" : "MongoDB Internal Client",
"version" : "4.0.10-5"
},
"os" : {
"type" : "Linux",
"name" : "CentOS Linux release 7.3.1611 (Core) ",
"architecture" : "x86_64",
"version" : "Kernel 3.10.0-693.21.1.std7a.el7.0.x86_64"
}
},
"active" : true,
"currentOpTime" : "2021-01-27T15:56:35.642+0800",
"opid" : 6877808,
"lsid" : {
"id" : UUID("d7b2aba5-ff9e-43b1-97ef-92b785439e22"),
"uid" : BinData(0,"o/6W9HojLAaDkSXLEEkW8L5LOrGfZaJEyQ8SL+OeBfY=")
},
"secs_running" : NumberLong(2),
"microsecs_running" : NumberLong(2949837),
"op" : "command",
"ns" : "apple.$cmd",
"command" : {
"createIndexes" : "foo",
"indexes" : [
{
"key" : {
"age" : 1
},
"name" : "age_1",
"background" : true
}
],
"lsid" : {
"id" : UUID("d7b2aba5-ff9e-43b1-97ef-92b785439e22")
},
"$clusterTime" : {
"clusterTime" : Timestamp(1611734186, 1613),
"signature" : {
"hash" : BinData(0,"qFgwHdz2+fl6oh+/1ZI9Mb6HPh4="),
"keyId" : NumberLong("6919692836459773955")
}
},
"$db" : "apple"
},
"msg" : "Index Build (background) Index Build (background): 583929/1765823 33%",
"progress" : {
"done" : 583930,
"total" : 1765823
},
"numYields" : 4562,
"locks" : {
"Global" : "w",
"Database" : "w",
"Collection" : "w"
},
"waitingForLock" : false,
"lockStats" : {
"Global" : {
"acquireCount" : {
"r" : NumberLong(4564),
"w" : NumberLong(4564)
}
},
"Database" : {
"acquireCount" : {
"w" : NumberLong(4565),
"W" : NumberLong(1)
}
},
"Collection" : {
"acquireCount" : {
"w" : NumberLong(4564)
}
}
}
},

 

重建索引:

 

db.table_name.reIndex()

 

 

 查看索引:

 

db.table_name.getIndexes()

 

 

 查看索引大小:

db.table_name.totalIndexSize()

 

 

查看当前数据库的所有索引

 

db.system.indexes.find()

 

 

删除某表指定索引:

 

db.table_name.dropIndex("name_index")

 

 

删除某表所有索引:

 

db.table_name.dropIndexes()

 

#############################

 



举报

相关推荐

0 条评论