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

前端 未结 7 1910
谎友^
谎友^ 2020-12-14 00:59

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

相关标签:
7条回答
  • 2020-12-14 01:12

    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);
    
    0 讨论(0)
  • 2020-12-14 01:17
    Document doc = new Document("name", Pattern.compile(keyword));
    collection.find(doc);
    
    0 讨论(0)
  • 2020-12-14 01:19

    To make it case insensitive:

    Document doc = new Document("name", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE));
    collection.find(doc);
    
    0 讨论(0)
  • 2020-12-14 01:21

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 01:24

    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.

    0 讨论(0)
  • 2020-12-14 01:28

    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.

    0 讨论(0)
提交回复
热议问题