Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do this MongoDB query using java?

Tags:

java

mongodb

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?

like image 309
zulu Avatar asked Jan 14 '13 07:01

zulu


People also ask

Can I use MongoDB with Java?

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT. You need to download the jar mongodb-driver-3.11.

What is BasicDBObject in Java?

public BasicDBObject(String key, Object value) Creates an object with the given key/value. Parameters: key - key under which to store value - value to store.


2 Answers

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);
like image 142
Rohit Jain Avatar answered Oct 12 '22 11:10

Rohit Jain


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.
like image 32
Rahul Avatar answered Oct 12 '22 10:10

Rahul