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
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 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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With