テキストインデックスの作成とTTLインデックスの作成を行います。
テキストインデックスの作成
testコレクションのnameフィールドにテキストインデックスを作成します。
テキストインデックスを作成する場合は、“text”を指定します。
[Mongoシェル]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| // テキストインデックスを作成 > db.test.createIndex({name:"text"}) { "numIndexesBefore" : 1, "numIndexesAfter" : 2, "createdCollectionAutomatically" : false, "ok" : 1 }
// インデックスの確認 > db.test.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "_fts" : "text", "_ftsx" : 1 }, "name" : "name_text", "weights" : { "name" : 1 }, "default_language" : "english", "language_override" : "language", "textIndexVersion" : 3 } ]
|
“name_text”というテキストインデックスを作成することができました。
TTLインデックスの作成
TTLインデックスを作成するためにはexpireAfterSecondsに秒数を指定します。
TTLインデックスに指定できるのは、Date型またはDate型を含む配列のフィールドです。
expireAfterSecondsで指定した秒数が経過したドキュメントを自動で削除することができます。
[Mongoシェル]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| // Dateフィールドを持つドキュメント作成 > db.ttltest.insert({time : ISODate("2021-06-09T10:20:05Z") } ) WriteResult({ "nInserted" : 1 })
// 作成したドキュメント確認 > db.ttltest.find() { "_id" : ObjectId("614bb5956e9eb9350501ee38"), "time" : ISODate("2021-06-09T10:20:05Z") }
// TTLインデックス作成 > db.ttltest.createIndex({time:1}, {expireAfterSeconds:60}) { "numIndexesBefore" : 1, "numIndexesAfter" : 2, "createdCollectionAutomatically" : false, "ok" : 1 }
// 作成したTTLインデックスの確認 > db.ttltest.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "time" : 1 }, "name" : "time_1", "expireAfterSeconds" : 60 } ]
// 60秒後にデータが自動削除されることを確認 > db.ttltest.find()
|
ttltestコレクションのtimeフィールドに、60秒でドキュメントが削除されるようにTTLインデックスを作成しました。
これでドキュメントが60秒経過後に自動的に削除されるようになります。