共計 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 問一下細節