Parameterized queries with Java and MongoDB - java

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

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.

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

Related

Mongodb Java access collection using regex

All of the documents in my collection contain a string field, "sourceTimeStamp" which looks like for example, 2018-11-15T14:20:06. I am trying to come up with a way to get a particular day's worth of data. I can access the data directly from RoboMongo using:
db.getCollection('archive_Nov_15_8pm_2018').find({ "tfms_object.sourceTimeStamp" : { $regex : /^2018-11-25*/}})
This returns many documents. But I need to do this using JAVA so I tried this:
DBCollection collection = db.getCollection(ARCHIVE_COLLECTION);
Pattern pat = Pattern.compile("^2018-11-15.*");
BasicDBObject query = new BasicDBObject("departureTime", pat);
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
query.put("$and", obj);
However, I get 0 documents returned. Any ideas?

Query Mongo DB using Java Driver

So I have a list of queryObjects (a class I created in my program) to query from a mongo DB with expressions all in an object like (pseudo code):
queryObject : { fild, operation, expression }
example : queryObject : { field : "pagePath", operation:"$in", expression:"/home"}
And the user can create as many queries as he/she wants. This works like charm until I have two queries with the same field name, example:
queryObject1 : { field : "pagePath", operation:"$in", expression:"/home"}
queryObject2 : { field : "pagePath", operation:"$regex", expression:"(.html)$"}
than I have: query.put(queryObject1) and query.put(queryObject2)
this command:
FindIterable<Document> iterable = statistics.find(query).projection(excludeId());
takes into consideration only the second put, what made me think that maybe it overrides the first. What can I do to prevent this from happening? is there a query syntaxe in Mongo that allows me to test that the Page Path is both a Home Page and ends with .html? knowing that this condition can change I always have to read the Query Object and create a MongoQuery in my program.
Assuming that your query object basically generates a Bson which can be used for Collection.find(), you can combine multiple Bsons via the Filters-utilities:
Bson b1 = firstQuery.convertToDbQuery(); // or however you do it... ;-)
Bson b2 = secondQuery.convertToDbQuery();
Bson combinedAsAnd = Filters.and(b1, b2);
collection.find(combinedAsAnd).projection(...)

Mongodb java springdata unable to get result for date equals query

I have inserted some test records to the mongo database with following structure.
{
"_id" : ObjectId("5563fe96a826638b48c77c26"),
"date" : ISODate("2015-05-02T07:00:00.326Z"),
"createdDate" : ISODate("2015-05-26T05:03:18.899Z"),
"updatedDate" : ISODate("2015-05-26T05:03:18.899Z"),
"status" : 0
}
Now when I try to query it using Spring data or via MongoDB I am always getting returned result list size to be 0.
Calendar calendar = Calendar.getInstance();
calendar.set(2015, 4, 2, 0, 0, 0);
Query query = new Query();
query.addCriteria(Criteria.where("date").is(calendar.getTime());
List<DateRecord> attendanceList = findAll(query, DateRecord.class);
System.out.println(attendanceList.size());
I am getting a very similar result for BasicDBObject, list of size 0.
DBCursor cursor;
BasicDBObject query1 = new BasicDBObject();
query1.append("date", calendar.getTime());
cursor = collection.find(query1);
System.out.println("Total objects returned "+cursor.size());
Any pointers on same will be highly appreciated. All I just want that data should be returned based upon year,month and day and any timestamp field values should be ignored.
I suggest using a different query - look for date greater than 2015-4-2 00:00:00 and explicitly less than 2015-4-3:00:00:00
Another approach, that I'm less enthusiastic about, would be to to add a field to the document just for the search purpose (e.g. "dateWithoutHour" calculated by java just before saving a document, and assuming data doesn't arrive from other sources). I don't like it, because I prefer my data to be pure logic and not change any time someone comes up with a new search requirement... but sometimes I had to resort to it).
And as always, when facing a difficult query it's tempting to consider $where , but I won't recommend it because it can't use indices.

Java & MongoDB query for date range

Before I start, I have already searched around for an answer to this issue and the best answer I could come up with is this question
I have one difference though. I have a table that maintains a history of many documents. Therefore I need to query on an ID as well as the date range. Here is what my query currently looks like in Java
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("id", id);
searchQuery.put("dateModified", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());
DBCursor cursor = table.find(searchQuery);
This returns no results. The MongoQuery that is generated by this block of code looks like this:
db.history.find({ "id" : 12345 , "dateModified" : { "$gte" : { "$date" : "2015-01-19T00:00:00.000Z"} , "$lte" : { "$date" : "2015-01-25T00:00:00.000Z"}}});
When I manually type this into MongoDB command line, this also returns no results. I currently have one record in the database for testing purposes that looks like this:
{
"id" : NumberLong(12345),
"dateModified" : ISODate("2015-01-21T19:42:28.044Z")
}
This object should clearly match the query, yet nothing is returning, any ideas?
EDIT: So it turns out that the string generated by the query object doesn't match the ISODate object in the database. I'd like to clarify that fromDate and toDate are both java.util.Date objects. I'm still not sure how to solve this though.
I figured out the issue. I don't understand the cause, but the issue is with the BasicDBObjectBuilder not using the Date object correctly. I switched to QueryBuilder and built the exact same query and it returned results.
fromDate must be of the type Date not the String representation. An ISODate in the MongoDB storage Engine is not equal to the String representation of the same date and so they do not match.

How to specify UUID in mongo $where clause

I have an object that was stored via mongo-java-driver. Object uses java.util.UUID for its _id field. Following is presentation of object via mongo shell:
> db.b.find()
{ "_id" : BinData(3,"zUOYY2AE8WZqigtb/Tqztw==") }
I have a requirement to process searching via $where clause. I use following code to do it:
Mongo m = new Mongo();
DBCollection coll = m.getDB("a").getCollection("b");
coll.save(new BasicDBObject("_id", UUID.randomUUID()));
// ??? - don't know what should be specified
DBObject query = new BasicDBObject("$where", "this[\"_id\"] == " + ???);
coll.find(query).count()
The question is what should I specify instead of ??? to make it work?
Thanks for any help.
My invesigation shown that only one way to do it is rewriting a query in object based way (I mean migration of $where clause part to BasicDBObject based query). In such case mongo-java-driver supports java.util.UUID without any additional effort.

Categories

Resources