MongDB 数据库使用技巧及注意事项

说明

本文记录MongoDB数据库的使用技巧总结,特性发现。

利用TTL特性实现数据定时删除

限制:

  • 你不能创建TTL索引,如果要索引的字段已经在其他索引中使用。
  • 索引不能包含多个字段。
  • 索引的字段必须是一个日期的 bson 类型。
test:PRIMARY> db.runoob.createIndex({"createdAt":1},{expireAfterSeconds:5*60}) # 对createdAt字段,“顺序”设置索引,-1表示倒序,过期时间设置5分钟,默认创建了索引名是"createdAt_1"
test:PRIMARY> db.runoob.insert({ "createdAt":new Date(), "name":"michael", "wish":"free" }) # 插入一条新纪录
test:PRIMARY> db.runoob.getIndexes() # 查看索引设置信息
test:PRIMARY> db.runCommand({collMod:"runoob", index:{keyPattern:{createdAt:1}, expireAfterSeconds:2*60 }}) # 修改过期时间为2分钟
test:PRIMARY> db.currentOp()  # 当TTL线程被激活后,可以从db.currentOp()
test:PRIMARY> db.runoob.dropIndex("createdAt_1") # 删除创建的索引
test:PRIMARY> db.runoob.createIndex({"createdAt":1},{expireAfterSeconds:2*60,name:"time_to_drop"}) # 加一个"name"属性,可以指定索引的名字
原文地址:https://www.cnblogs.com/michael-xiang/p/10468236.html