Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query mongodb with “like” using the java api?

this question is very similar to another post

I basically want to use the mongodb version of the sql "like" '%m%' operator

but in my situation i'm using the java api for mongodb, while the other post is using mongodb shell

i tried what was posted in the other thread and it worked fine

db.users.find({"name": /m/}) 

but in java, i'm using the put method on the BasicDBObject and passing it into the find() method on a DBCollections object

BasicDBObject q = new BasicDBOBject(); q.put("name", "/"+m+"/"); dbc.find(q); 

but this doesn't seem to be working.

anyone has any ideas?

like image 571
Khon Lieu Avatar asked Apr 09 '11 23:04

Khon Lieu


People also ask

Can I connect MongoDB with Java?

Connecting via Java. Assuming you've resolved your dependencies and you've set up your project, you're ready to connect to MongoDB from your Java application. Since MongoDB is a document database, you might not be surprised to learn that you don't connect to it via traditional SQL/relational DB methods like JDBC.

Which method is used to query data from MongoDB collection?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.


2 Answers

You need to pass an instance of a Java RegEx (java.util.regex.Pattern):

BasicDBObject q = new BasicDBObject(); q.put("name",  java.util.regex.Pattern.compile(m)); dbc.find(q); 

This will be converted to a MongoDB regex when sent to the server, as well as any RegEx flags.

like image 64
Brendan W. McAdams Avatar answered Sep 25 '22 12:09

Brendan W. McAdams


To make it case insensitive:

Document doc = new Document("name", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE)); collection.find(doc); 
like image 41
Andres Avatar answered Sep 21 '22 12:09

Andres