久しぶりに、MongoDB の 登録処理を実装する機会があったのですが、
3.0 から IndexOptions
というクラスを使用して、
index 作成ができるようになったらしく、試してみた結果を記載します。
参考
MongoDB java driver の version
3.2.2
です。
<!-- MongoDB -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
実装
- TTL index を作成する
IndexOptions を生成、
Indexes を使って、以下の通り実装ができます。
IndexOptions createdAtIndexOptions =
new IndexOptions()
.expireAfter(settings.getExpirationTime(), TimeUnit.MINUTES)
.background(true)
.name("createdAt_ttl_index");
Bson createdAt = Indexes.ascending("createdAt");
collection.createIndex(createdAt, createdAtIndexOptions);
以前の実装に比べると、すっきりかけるようになった気がします。
以上です。
コメント