Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent for a MongoDB select query

Tags:

java

mongodb

I would like to retrieve the following information:

select names from database where names like 'Jon';

but for MongoDB in Java. Essentially, it should return all names that contain the word Jon in them, like Jonathan, Jong etc etc. I know that there is the $in operator in MongoDB, but how do I do the same in Java, using the Java driver? I've been trying to look for it everywhere but am getting nothing. I've tried: query = new BasicDBObject("names", new BasicDBObject("$in", "Jon"));, and query = new BasicDBObject("names", new BasicDBObject("$in", Jon));

But neither of them worked :( Please help!

like image 610
CodingInCircles Avatar asked Dec 04 '12 21:12

CodingInCircles


2 Answers

The MongoDB Java driver equivalent of that SELECT statement would be:

BasicDBObject fields = new BasicDBObject().append("name", 1); // SELECT name
BasicDBObject query = new BasicDBObject().append("name", "Jon"); // WHERE name = "Jon"
DBCursor results = yourCollection.find(query, fields); // FROM yourCollection

When you want to search for a part of a string, you can use the $regex operator:

query = new BasicDBObject("name", new BasicDBObject("$regex", "Jon"));

This will get you all objects where the name matches the regular expression Jon, which is everything which includes the string "Jon" anywhere.

like image 172
Philipp Avatar answered Oct 31 '22 10:10

Philipp


Check the Mongo-Java official site, plus a nice library for mapping mongo objects

like image 24
George D Avatar answered Oct 31 '22 09:10

George D