Java equivalent for a MongoDB select query
java, mongodb
Solution
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.
Problem
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!