Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB query in java

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

like image 702
Global Warrior Avatar asked May 04 '12 06:05

Global Warrior


People also ask

Can I use MongoDB with Java?

Assuming you already have Java installed on your system, and your favorite IDE fired up and ready to go, the first thing you're going to want to do is get the MongoDB Java Driver. Most IDEs will pick up resources configured in Gradle or Maven, either of which can be used to install the driver.

What is a MongoDB query?

What is MongoDB Query? MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries provide the simplicity in process of fetching data from the database, it's similar to SQL queries in SQL Database language.

Can we write queries in MongoDB?

The $in operator allows you to write queries that will return documents with values matching one of multiple values held in an array. The following example query includes the $in operator, and will return documents whose name value matches either Everest or K2 : db. peaks.


1 Answers

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);
like image 132
Benoît Guérout Avatar answered Oct 13 '22 23:10

Benoît Guérout