6

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");
...
2
  • Reading about MongoDb, it seems to me that because a mongodb query's input isn't really a command but rather a json filter, there's no concern about someone injecting malicious values. Everything is handled as data and not commands, hence no need for protection. Am I right? Commented Sep 13, 2016 at 5:30
  • 1
    I'm totally wrong. See a great example on NoSql injection here - blog.websecurify.com/2014/08/hacking-nodejs-and-mongodb.html Commented Sep 13, 2016 at 5:40

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

OK, that makes sense. So, I guess what I'm looking for is a third party Java API on top of the Mongo that does this - a higher level of abstraction.
You don't really need another layer of abstraction of course; you can just do it yourself.
@loveNoHate - I'm not sure eval can be put as a value in the json filter.
For complex queries, you'll find yourself creating a lot of objects for each query. I do not feel safe re-using those. Depending on which language / driver you're using, you can't really be sure of query-objects life cycle (or if they're thread safe).
3

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.