12

I have to write a complex mongo query using java but am not able to do it.

The mongo query looks like this:

db.video.findOne( { 
    $or: [ 
        { key1: { $in : [764] } }, 
        { key2: {$in : [list2] } }, 
        { $and [ { key2 : 3}, {key4:67} ] } 
    ]
})

I have to write the above query using the QueryBuilder class. In what way can I do it?

Thanks

2 Answers 2

17

Using QueryBuilder your query should look like this

DBObject query = QueryBuilder.start().or(
    QueryBuilder.start("key1").in(764).get(),
    QueryBuilder.start("key2").in(keys).get(),
    QueryBuilder.start().and("key3").is(3).and("key4").is(64).get()
 ).get();

Consider using jongo (an API over mongo-java-driver) you can simply copy/paste queries from the shell :

collection.findOne("{$or:[{key1: {$in:[764]}},{key2:{$in:[#]}}, {$and:[{key3:3},{key4:67}]}]}", keys).as(People.class);
Sign up to request clarification or add additional context in comments.

1 Comment

But how to execute query(DBObject) ?
6

I had the same problem and i got a solution in another way :

ArrayList orList = new ArrayList();
ArrayList andList = new ArrayList();

orList.add(new BasicDBObject("key1", new BasicDBObject("$in", 764)));                  
orList.add(new BasicDBObject("key2", new BasicDBObject("$in", list2)));

andList.add(new BasicDBObject("key2", 3));
andList.add(new BasicDBObject("key4", 67));

orList.add(new BasicDBObject("$and", andList));

BasicDBObject query = new BasicDBObject("$or", orList);

1 Comment

But how to execute query(DBObject) ?

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.