如何使用 java api 用“like"查询 mongodb? [英] How to query mongodb with “like” using the java api?

查看:41
本文介绍了如何使用 java api 用“like"查询 mongodb?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与另一个post

我基本上是想用mongodb版本的sql "like" '%m%' operator

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

但在我的情况下,我使用 mongodb 的 java api,而另一篇文章使用的是 mongodb shell

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/})

但在 java 中,我使用 BasicDBObject 上的 put 方法并将其传递给 DBCollections 对象上的 find() 方法

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);

但这似乎不起作用.

有人有什么想法吗?

推荐答案

你需要传递一个 Java RegEx 的实例(java.util.regex.Pattern):

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);

这将在发送到服务器时转换为 MongoDB 正则表达式,以及任何正则表达式标志.

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

这篇关于如何使用 java api 用“like"查询 mongodb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆