Skip to content
Konstantin Triger edited this page Nov 11, 2019 · 5 revisions

Get in Control of Your Mongo Queries

Restaurant repository example:

import static co.streamx.fluent.mongo.grammar.FluentFilters.eq;
import static co.streamx.fluent.mongo.grammar.FluentSorts.descending;
import static co.streamx.fluent.mongo.grammar.FluentUpdates.combine;
import static co.streamx.fluent.mongo.grammar.FluentUpdates.currentDate;
import static co.streamx.fluent.mongo.grammar.FluentUpdates.set;

// 100% type safe, compiler verified and refactoring friendly
@Service
public class RestaurantRepository {

    private static final QueryBuilder<Restaurant> builder =
                         FluentMongo.queryBuilder(Restaurant.class);

    @Autowired
    private MongoCollection<Restaurant> collection;

    // arguments are captured and passed automatically
    public MongoIterable<Restaurant> getBestInCategory(int minStars, String category) {

        Bson filter = builder.filter(r -> r.getStars() >= minStars &&
                                          r.getCategories().contains(category));
        Bson order = builder.sort(r -> descending(r.getStars()));

        return collection.find(filter).sort(order);
    }

    public void updatePhone(String id, String phone) {
        Bson filter = builder.filter(r -> eq(id));
        Bson update = builder.update(r -> combine(set(r.getContact().getPhone(), phone),
                                                  currentDate(r.getLastModified())));

        collection.updateOne(filter, update);
    }
}

Getting Started

Clone this wiki locally