Reputation: 542
I'd like to query a MongoDB collection dynamically from an Apache Camel route. The Apache Camel docs show how to query a collection using a constant
value:
from("direct:findOneByQuery")
.setHeader(MongoDbConstants.CRITERIA, Filters.eq("name", "Raul Kripalani"))
.to("mongodb:myDb?database=flights&collection=tickets&operation=findOneByQuery")
.to("mock:resultFindOneByQuery");
And while I'm sure that's useful to some folks, I was trying to query a collection with a dynamically generated value, using an Exchange header for instance. How do you do that?
Upvotes: 1
Views: 809
Reputation: 542
For starters, that statement above won't compile. It was pointed out to me in another question that there's an error in current Apache Camel MongoDB documentation and that the setHeader
line above should read:
.setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("name", "Raul Kripalani"))
The way I ended up doing this was by creating an anonomyous Expression
:
import com.mongodb.client.model.Filters;
import com.mongodb.BasicDBObject;
import org.bson.conversions.Bson;
@Component
public class NotifyClientRoute extends RouteBuilder {
public static final String NOTIFY_CLIENT_URI = "direct:notifyClient";
@Override
public void configure() throws Exception {
from(NOTIFY_CLIENT_URI)
.log("Determining which client gets the deletion request next for DR request '${header.drRequestId}'.")
.setHeader(MongoDbConstants.CRITERIA, new Expression() {
@Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
String drRequestId = exchange.getIn().getHeader("drRequestId", String.class);
Bson equalsClause = Filters.eq("drRequestId", drRequestId);
// Alternatively:
// Bson equalsClause = new BasicDBObject("drRequestId", new BasicDBObject("$eq", drRequestId));
return exchange.getContext().getTypeConverter().convertTo(type, equalsClause);
};
})
.to("mongodb:mongoClient?database=mydb&collection=mycollection&operation=findOneByQuery")
.log("Query returned: '${body}'");
}
}
Additional note: I didn't come up with that return statement in the Expression
. I was running into type errors, and so I looked at what another Apache Camel Expression
implementations included in the Camel libraries were returning, and I found that return clause.
Upvotes: 1