Java equivalent for MongoDB select query

I would like the following information:

select names from database where names like 'Jon'; 

but for MongoDB in Java. Essentially, it should return all names containing the word Jon in them, for example Jonathan, Jong, etc. I know there is a $in operator in MongoDB, but how can I do the same in Java using the Java driver? I tried to find it everywhere, but I get nothing. I tried: query = new BasicDBObject("names", new BasicDBObject("$in", "Jon")); and query = new BasicDBObject("names", new BasicDBObject("$in", Jon));

But none of them worked: (Please help!

+6
source share
3 answers

The Java MongoDB driver, equivalent to this SELECT statement, will look like this:

 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 

If you want to find part of a string, you can use the $regex operator:

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

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

+10
source

Check out the official Mongo-Java website, as well as the nice library for displaying Mongo objects

+1
source

The $in statement in MongoDB is similar to the IN statement in SQL. For example, it can be used to execute SQL-like queries like

 SELECT * FROM table WHERE id IN {1, 4, 6, 7, 9} 

That is why this does not work for you. Use regular expressions, as others have already pointed out.

0
source

All Articles