When looking on the official Java driver API, we can see an effort to make an API as fluent as possible:
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")));
Yet, there are many issues:
- All fields are Strings without auto completion.
- No type safety on operators (Is
starsa number?! Is
categoriesa collection (?!) of Strings or …?!).
- Do we really like using
>=?! I mean, is it easy to read and understand this expression?
- And finally, when the schema changes, we are back to 80’ with find-replace…
There is a simple and effective solution to those issues — FluentMongo, which adds the missing ingredient to the API — type safety and Java integration. It lets you use normal Java to write filters, projections, updates, sorts and indexes. For example:
collection.find(builder.filter(r -> r.getStars() >= 2 && r.getStars() < 5 && r.getCategories().contains("Bakery")));
As an author of this OSS library, I would be happy to learn about the value and usability of this solution.