How to use regex inside query using morphia?

Mongodb allows a pattern / pattern / regex expression without using the $ regex expression.

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

How can I do this using morphine?

If I give field criteria with a field operator, like a value like "java.util.regex.Pattern", then the equivalent query generated in $ in: [$ regex: 'given pattern'], which will not return the expected results at all.

Waiting: $ in: [/ pattern1 here /, / pattern2 here /] Actual use of the 'Pattern' object: $ in: [$ regex: / pattern1 here /, $ regex: / pattern 2 here /]

+4
source share
2

, , 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"),
  "tags": [
    "India",
    "Australia",
    "Indonesia"
  ]
}
{
  "_id": ObjectId("54f3ac4da63f282f56de64be"),
  "tags": [
    "Island",
    "Antigua"
  ]
}
{
  "_id": ObjectId("54f3ac6da63f282f56de64c0"),
  "tags": [
    "Israel"
  ]
}
{
  "_id": ObjectId("54f3ad17a63f282f56de64c1"),
  "tags": [
    "Germany",
    "Indonesia"
  ]
}

. , . /^I/i, , Pattern.CASE_INSENSITIVE Java.

+4

Single RegEx

.filter(), .criteria() .field()

query.filter("email", Pattern.compile("reg.*exp"));
// or
query.criteria("email").contains("reg.*exp");
// or
query.field("email").contains("reg.*exp");

Morphia :

find({"email": { $regex: "reg.*exp" } })

RegEx

query.or(
    query.criteria("email").contains("reg.*exp"),
    query.criteria("email").contains("reg.*exp.*2"),
    query.criteria("email").contains("reg.*exp.*3")
);

Morphia :

find({"$or" : [ 
            {"email": {"$regex": "reg.*exp"}},
            {"email": {"$regex": "reg.*exp.*2"}},
            {"email": {"$regex": "reg.*exp.*3"}}
        ]
    })

,

$regex $in. MongoDB 3.4

:

Pattern[] patterns = new Pattern[] {
    Pattern.compile("reg.*exp"),
    Pattern.compile("reg.*exp.*2"),
    Pattern.compile("reg.*exp.*3"),
};
query.field().in(patterns);

, :)

0

All Articles