mongodbcollationjongo

Collation with jongo


I use MongoDB via Jongo (a Java client), and I need to sort results in a case-insensitive way for a particular query.

MongoDB's documentation states that an index should be created with a certain collation level, and that the queries should use the same configuration :

db.fruit.find( {type: "apple"} )
        .collation( {locale: 'en', strength: 2} )

Creating the index was easy; but I cannot find where to pass the collation configuration with Jongo's query API.

Find query = myCollection.find(match);  // No .collation() method here

Any idea ?


Solution

  • Use a query modifier which can be set on DBCursor by implementing QueryModifier and pass it in the 'with' method:

    friends.find().with(new QueryModifier() {
         public void modify(DBCursor cursor) {
             cursor.setCollation(
                Collation.builder().collationStrength(CollationStrength.SECONDARY).
                locale("en").
                build())
         }
    }).as(Friend.class);