Mark Hansen
Mark Hansen

Reputation: 1062

Parameterized queries with Java and MongoDB

Can you do parameterized queries with Java and MongoDB - kind of like prepared statements with JDBC?

What I'd like to do is something like this. Set up a query that takes a date range - and then call it with different ranges. I understand that DBCursor.find(...) doesn't work this way - this is 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");
...

Upvotes: 6

Views: 6492

Answers (2)

Benoît Guérout
Benoît Guérout

Reputation: 1997

You should use Jongo, an API over mongo-java-driver.

Here is an example with 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);

Upvotes: 3

Derick
Derick

Reputation: 36784

MongoDB itself doesn't support anything like this, but then again, it doesn't take too much sense as it needs to send the query over to the server every time anyway. You can simply construct the object in your application yourself, and just modify specific parts by updating the correct array elements.

Upvotes: 4

Related Questions