Mongo DB query in java

Global Warrior picture Global Warrior · May 4, 2012 · Viewed 12.6k times · Source

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

Answer

Benoît Guérout picture Benoît Guérout · May 4, 2012

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