All posts for the month April, 2018

Java MongoDB Collation

Since 3.4, MongoDB now supports specifying collation, which basically means that sorting case insensitive can now be done by the DB natively.

Here’s how to do it in an example method:

public static MongoCursor getDatatableIterator(final String collection, final Bson query, Object sort, final Integer skip, final Integer limit) {
if (sort != null && !sort.getClass().equals(Bson.class)) {
sort = makeSortList(sort);
Collation caseInsensitive = Collation.builder().collationStrength(CollationStrength.SECONDARY).locale("en").build();
if (query == null) {
return getDocuments(collection).collation(caseInsensitive).sort((Bson)sort).skip(skip).limit(limit).iterator();
return getDocuments(collection).collation(caseInsensitive).sort((Bson)sort).filter(query).skip(skip).limit(limit).iterator();