12

I have to write a simple MongoDB query using java but am not able to do it.

The mongo query looks like this:

db.yourCollection.find({"$where" : "this.startDate < this.endDate"})

I have to write the above query using the QueryBuilder class. But am not able to do it in MongoDB java driver.

BasicDBObject document = new BasicDBObject();
document.put("id", 1001);
document.put("intValue", 1200);
document.put("updateValue", 2100);

DBObject query = QueryBuilder.start("intValue").lessThan("updateValue").get();
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println("Result : -"+cursor.next());}

The above code does not return any results. But if changed to updateValue into 2100 it is giving result. My question here is lessThan takes object as input parameter. Then how can I pass document field as an input parameter?

2 Answers 2

14

Ideally your mongoDB query should be like this: -

db.yourCollection.find({"startDate": {$lt: endDate}})

which can be written in Java like this: -

BasicDBObject query = new BasicDBObject("startDate", new BasicDBObject("$lt", endDate);
DBCursor cursor = coll.find(query);

You can take a look at Official Tutorial


If you want to use QueryBuilder, you can do it like this: -

DBObject query = QueryBuilder.start("startDate").lessThan("endDate").get();
DBCursor cursor = coll.find(query);
Sign up to request clarification or add additional context in comments.

1 Comment

The above query builder is not working. if the "endDate" is a field in the same document. It is working if i give the constant value instead of endDate in the QueryBuilder. Moreover the BasicDBObject doesn't accept the endDate field name in thje second parameter
5

QueryBuilder helps construct complex queries to retrieve data from a collection in mongo db. You can use the QueryBuilder like this.

BasicDBObject document = new BasicDBObject();
QueryBuilder qb = new QueryBuilder();
qb.or(new QueryBuilder().put("starting_date").is(null).put("ending_date").is(null).get(),
                new QueryBuilder().put("starting_date").lessThanEquals("ending_date").get());
document.putAll(qb.get());
DBCursor cursor = getDbCollection().find(document)
  • QueryBuilder qb = new QueryBuilder(), instantiates a new QueryBuilder.
  • The logic build by the QueryBuilder in the example above is; (starting date = null and ending date = null) or (starting date <=ending date)
  • document.putAll(qb.get()) adds the logic constructed to the DBObject.

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.