This library provides wrappers around MongoDB's asynchronous Java API to make programming to it easier - particularly chaining together chunks of work that should happen in sequence, asynchronously.
Read the Javadoc
It uses the async promises library under the hood, and also provides builder classes for things like updates, which have fairly fussy and non-typesafe syntax in MongoDB.
To use, simply create a CollectionPromises<T>
over a native MongoDB MongoCollection<T>
,
and use the instance methods on that.
The point is to provide a clean abstraction for chaining together asynchronous database operations.
AsyncPromise<Bson, Long> promise = p.find().descendingSortBy("ix").withBatchSize(20).find(new FindReceiver<List<Document>>(){
int total = 0;
@Override
public void withResults(List<Document> obj, Trigger<Boolean> trigger, PromiseContext context) throws Exception {
total += obj.size();
System.out.println("GET ONE BATCH " + obj.size() + " TOTAL " + total);
all.addAll(obj);
trigger.trigger(true, null);
}
}).then(new SimpleLogic<Void,Void>(){
@Override
public void run(Void data, Trigger<Void> next) throws Exception {
nextWasRun.set(true);
next.trigger(null, null);
}
}).then(new Document(), p.count().maxTime(10, TimeUnit.SECONDS).count());
promise.start(new Document(), new Trigger<Long>(){
@Override
public void trigger(Long count, Throwable thrown) {
countHolder.set(count);
waitForAllResults.countDown();
}
});
Similar code using JDK 8's lambads:
AsyncPromise<Void, Long> promise = p.query().equal("name","foo").build()
.descendingSortBy("ix").withBatchSize(20).find(
(List<Document> obj, Trigger<Boolean> trigger, PromiseContext context)-> {
all.addAll(obj);
trigger.trigger(true, null);
}).then((Void data, Trigger<Void> next) -> {
nextWasRun.set(true);
next.trigger(null, null);
}).then(new Document(), p.count().maxTime(10, TimeUnit.SECONDS).count())
.start();
A number of builder classes are included to make things easy - in each case, they return an AsyncPromise you can start to execute the operation or chain it together with other operations.
For example, querying can use a nice QueryBuilder
(which lets you specify things like $in, $gt,
partial or complete subdocument matches, etc.):
CollectionPromises<Document> p = new CollectionPromises<>(someCollection);
p.query().equal("skidoo", 23).embedded("foo").embedded("bar").equal("meaning", 42)
.build()
.build()
.elemMatch("array").equal("name", "Joe").greaterThan("age", 18).lessThan("age", 65).build()
.in("city", "Boston", "New York", "Shutesbury").build()
results in a MongoDB query as follows:
{
skidoo : 23,
foo.bar.meaning : 42,
logins : {
country : USA
},
city : {
$in : [Boston, New York, Shutesbury]
},
people : {
$elemMatch : {
name : Joe,
age : {
$gt : 18, $lt : 65
}
}
}
}
This then drops you into a FindBuilder
which lets you configure cursor attributes like limit
and sort order, which in turn builds a promise you can run.