How to query mongodb with “like” using the java ap

2019-01-22 06:15发布

问题:

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?

回答1:

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.



回答2:

You must first quote your text and then use the compile to get a regex expression:

q.put("name",  Pattern.compile(Pattern.quote(m)));

Without using java.util.Pattern.quote() some characters are not escaped.

e.g. using ? as the m parameter will throw an exception.



回答3:

To make it case insensitive:

Document doc = new Document("name", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE));
collection.find(doc);


回答4:

In spring data mongodb, this can be done as:

Query query = new Query();
query.limit(10);        
query.addCriteria(Criteria.where("tagName").regex(tagName));
mongoOperation.find(query, Tags.class);


回答5:

Document doc = new Document("name", Pattern.compile(keyword));
collection.find(doc);


回答6:

Might not be the actual answer, ( Executing the terminal query directly )

public void displayDetails() {
    try {
        // DB db = roleDao.returnDB();
        MongoClient mongoClient = new MongoClient("localhost", 5000);
        DB db = mongoClient.getDB("test");
        db.eval("db.test.update({'id':{'$not':{'$in':[/su/]}}},{$set:{'test':'test3'}},true,true)", new Object[] {});
        System.out.println("inserted  ");

    } catch (Exception e) {
        System.out.println(e);
    }
}