加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在使用morphia的查询中使用正则表达式?

发布时间:2020-12-14 06:00:25 所属栏目:百科 来源:网络整理
导读:Mongodb允许正则表达式模式/模式/而不使用$regex表达式. http://docs.mongodb.org/manual/reference/operator/query/in/ 我如何使用吗啡呢? 如果我给字段运算符作为字段运算符和类型“java.util.regex.Pattern”的值,那么生成的等效查询 $in:[$regex:’gi
Mongodb允许正则表达式模式/模式/而不使用$regex表达式.

http://docs.mongodb.org/manual/reference/operator/query/in/

我如何使用吗啡呢?

如果我给字段运算符作为字段运算符和类型“java.util.regex.Pattern”的值,那么生成的等效查询
$in:[$regex:’given pattern’]根本不会返回预期的结果.

期望:$in:[/ pattern1 here /,/ pattern2 here /]
实际使用’Pattern’对象:$in:[$regex:/ pattern1 here /,$regex:/ pattern 2 here /]

解决方法

我不完全确定你的代码示例是什么,但这是一个有效的Morphia代码片段:

Pattern regexp = Pattern.compile("^" + email + "$",Pattern.CASE_INSENSITIVE);
mongoDatastore.find(EmployeeEntity.class).filter("email",regexp).get();

请注意,这真的很慢.它不能使用索引,并且总是需要完整的集合扫描,所以不惜一切代价避免它!

更新:我添加了一个特定的代码示例. $in不需要在数组内搜索.只需使用/ ^ I /就像在字符串中一样:

> db.profile.find()
{
  "_id": ObjectId("54f3ac3fa63f282f56de64bd"),"tags": [
    "India","Australia","Indonesia"
  ]
}
{
  "_id": ObjectId("54f3ac4da63f282f56de64be"),"tags": [
    "Island","Antigua"
  ]
}
{
  "_id": ObjectId("54f3ac5ca63f282f56de64bf"),"tags": [
    "Spain","Mexico"
  ]
}
{
  "_id": ObjectId("54f3ac6da63f282f56de64c0"),"tags": [
    "Israel"
  ]
}
{
  "_id": ObjectId("54f3ad17a63f282f56de64c1"),"tags": [
    "Germany","Indonesia"
  ]
}
{
  "_id": ObjectId("54f3ad56a63f282f56de64c2"),"tags": [
    "ireland"
  ]
}
> db.profile.find({ tags: /^I/ })
{
  "_id": ObjectId("54f3ac3fa63f282f56de64bd"),"Antigua"
  ]
}
{
  "_id": ObjectId("54f3ac6da63f282f56de64c0"),"Indonesia"
  ]
}

注意:数组中的位置没有区别,但搜索区分大小写.如果不需要,请使用/ ^ I / i或Java中使用Pattern.CASE_INSENSITIVE.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读