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!
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.
Check the Mongo-Java official site, plus a nice library for mapping mongo objects
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