private MongoCollection<Document> createCollection(String collectionName) {
String indexFieldName1 = "itemId";
String indexFieldName2 = "time";
MongoCollection<Document> mongoCollection = this.database.getCollection(collectionName);
if (mongoCollection == null) {
this.database.createCollection(collectionName);
mongoCollection = this.database.getCollection(collectionName);
}
IndexOptions indexOptions1 = new IndexOptions().unique(false)
.background(false).name(indexFieldName1);
Bson keys1 = new Document(indexFieldName1, Integer.valueOf(1));
mongoCollection.createIndex(keys1, indexOptions1);
IndexOptions indexOptions2 = new IndexOptions().unique(false)
.background(false).name(indexFieldName2);
Bson keys2 = new Document(indexFieldName2, Integer.valueOf(1));
mongoCollection.createIndex(keys2, indexOptions2);
return mongoCollection;
}
References
https://www.programcreek.com/java-api-examples/?class=com.mongodb.client.MongoCollection&method=createIndex
Related