如何使用java api查询“like”的mongodb? [英] How to query mongodb with “like” using the java api?
问题描述
这个问题与另一个帖子
非常相似b$ b
我基本上想使用mongodb版本的sqllike'%m%'运算符
但是在我的情况下,我'm使用java api for mongodb,而另一个帖子是使用mongodb shell
我尝试了在其他线程中发布的内容,它工作正常
db.users.find({name:/ m /})
$ p
但是在java中,我在BasicDBObject上使用put方法,并将它传递到DBCollections对象的find()方法中。
BasicDBObject q = new BasicDBOBject();
q.put(name,/+ m +/);
dbc.find(q);
但是这似乎不起作用。
任何人有什么想法?
解决方案Java RegEx实例( java.util.regex .Battern ):
$ p $BasicDBObject q = new BasicDBObject();
q.put(name,java.util.regex.Pattern.compile(m));
dbc.find(q);
这将在发送到服务器时转换为MongoDB正则表达式,以及任何RegEx标志。
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?
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.
这篇关于如何使用java api查询“like”的mongodb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!