Parameterized Queries with Java and MongoDB
Can you execute parameterized queries using Java and MongoDB - sort of like prepared statements with JDBC?
What I would like to do is something like this. Configure a query that accepts a date range, and then call it with different ranges. I understand that DBCursor.find(...)
does not work this way - it is a kind of pseudo code to illustrate what I'm looking for.
DBCollection dbc = ... DBObject pQuery = (DBObject) JSON.parse("{'date' : {'$gte' : ?}, 'date' : {'$lte' : ?}}"); DBCursor aprilResults = dbc.find(pQuery, "2012-04-01", "2012-04-30"); DBCursor mayResults = dbc.find(pQuery, "2012-05-01", "2012-05-31"); ...
MongoDB itself does not support anything like this, but again, it does not take too much sense, because in any case, it must send a request to the server. You can simply create an object in your application yourself and simply change certain parts by updating the correct array elements.
You must use the Jongo API on top of the mongo-java driver.
Here is an example with a parameterized query:
collection.insert("{'date' : #}", new Date(999)); Date before = new Date(0); Date after = new Date(1000); Iterable<Report> results = collection.find("{'date' : {$gte : #}, 'date' : {$lte : #}}", before, after).as(Report.class);