Skip to content

mongo api

WinChua edited this page Jul 20, 2020 · 5 revisions
db.hello.createIndex(key, option)
e.g:
    db.hello.createIndex({"key": 1}, {"expireAfterSeconds": 60})

1.1 key

{"key": 1}, 1 表示升序, -1 表示降序;

1.2 option

option 说明
background 是否在后台线程中创建索引, 后台创建索引, 不会阻塞别的读写操作, 默认值是false
unique 指定唯一索引, 默认为false, 为true, mongo将不会接受,重复的key
name 索引名称, 如果没有指定的话, mongo将会指定一个默认的名称: ${key}_${sort_order}
expireAfterSeconds 整型值, 指定了整个文档的过期时间, key的值需要是 date类型
还有别的option暂时不知道怎么用
db.hello.createIndex({"createAt": 1}, {"expireAfterSeconds": 60})
db.hello.insert({"uin": 1934203186, "createAt": new Date()})

mongo文档过期删除策略: mongo会有一个后台线程, 默认是每分钟执行一次, 可能会存在某些document过期了,但是某一段时间还是生效的

2. 查看分片相关统计操作

db.table.stats().shards : 查看某个table下分片情况是否
[sh.shardCollection](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-indexes)("test.hello", {uin: 1}, true) : 对test.hello进行分片, 指定uin作为分片key, true表示uin是一个唯一索引;
如果需要进行shard操作的table非空, 那么需要手动创建需要的索引. 如果是空的, 命令会自动为你创建一个索引;
db.table.getIndexes() : 查看table下的所有索引情况;
db.runCommand({shardcollection:"test.taginfo", unique: true, key: {uin:1} }) : 也是对某个table进行分片的操作, 需要先使用use admin命令切换到admin下
db.printShardingStatus()

Clone this wiki locally