prateek3636
prateek3636

Reputation: 165

Mongo Java query for and/or combination

I need a Java driver mongo query for and/or combination - for ex -

suppose I have a collection user have 3 field named a, b, c.

Now I have to perform find query like -

user.find({$and :[{"a":"text"},{$or :[{"b":"text"},{"c":"text"}]}]})

This mongo console query give correct result. How I apply this with JAVA mongo driver.

Please help Thanks in advance

Upvotes: 1

Views: 3599

Answers (1)

nilesh virkar
nilesh virkar

Reputation: 459

You can use following query

DBCollection userCollection = db.getCollection("collection");

BasicDBObject orQuery = new BasicDBObject();
List<BasicDBObject> obj1 = new ArrayList<BasicDBObject>();
obj1.add(new BasicDBObject("a", "text"));
obj1.add(new BasicDBObject("b", "text"));
orQuery.put("$or", obj1);

BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("c", "text"));
obj.add(orQuery);
andQuery.put("$and", obj);

System.out.println(andQuery.toString());

DBCursor cursor = userCollection.find(andQuery);
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Upvotes: 7

Related Questions