MongoDB中怎么实现过期索引

49次阅读
没有评论

共计 1156 个字符,预计需要花费 3 分钟才能阅读完成。

自动写代码机器人,免费开通

这篇文章给大家介绍 MongoDB 中怎么实现过期索引,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

范例:设置过期索引,10 秒后过期
db.phones.createIndex({time :1},{expireAfterSeconds:10})
{
  createdCollectionAutomatically : true,
  numIndexesBefore : 1,
  numIndexesAfter : 2,
  ok : 1
}

再插入数据:
db.phones.insert({tel :110, code :110, time :new Date()});
db.phones.insert({tel :111, code :111, time :new Date()});
db.phones.insert({tel :112, code :112, time :new Date()});
db.phones.insert({tel :113, code :113, time :new Date()});
db.phones.insert({tel :114, code :114, time :new Date()});

查看:
db.phones.find();
{_id : ObjectId( 5992b97f0184ff511bf02bb2), tel : 110, code : 110, time : ISODate(2017-08-15T09:06:07.042Z) }
{_id : ObjectId( 5992b97f0184ff511bf02bb3), tel : 111, code : 111, time : ISODate(2017-08-15T09:06:07.046Z) }
{_id : ObjectId( 5992b97f0184ff511bf02bb4), tel : 112, code : 112, time : ISODate(2017-08-15T09:06:07.084Z) }
{_id : ObjectId( 5992b97f0184ff511bf02bb5), tel : 113, code : 113, time : ISODate(2017-08-15T09:06:07.133Z) }
{_id : ObjectId( 5992b9800184ff511bf02bb6), tel : 114, code : 114, time : ISODate(2017-08-15T09:06:08.142Z) }

等到 10 秒以后(永远不会那么准确)锁保存的数据就会消失。这样的特性在进行一些临时数据保存的时候非常有帮助。如果没有这个特性,而使用关系型数据库是非常麻烦的。

关于 MongoDB 中怎么实现过期索引就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向 AI 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计1156字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)