简体   繁体   中英

Use the $in Operator with a Regular Expression in Java

I am trying to write $in query with $regex in mongo + java. It is working fine from mongo shell and I am getting the results:

db.getCollection('collection').find({ "_id" : { "$in" : [ /^1332444344/]}})

However, when I try to executed from my java app, I get no results:

DBCollection collection = db.getCollection("collection");
BasicDBObject query = new BasicDBObject();
inQuery.put("_id", new BasicDBObject("$in", input));
DBCursor cursor = collection.find(query);

// This returns no results
// Query: { "_id" : { "$in" : [ { "$regex" : "/^1332444344/"} ] }}
input = Lists.newArrayList(Pattern.compile("/^1332444344/"));

// The following as well returned nothing
// Query: { "_id" : { "$in" : [ "/^1332444344/" ] }}
input = Lists.newArrayList("/^1332444344/"));

The Java Code is adding the double quotes around regex and it seems this is causing the issue.

I also tried the following but got a json parse exception:

BasicQuery bq = new BasicQuery("{ \"_id\" : { \"$in\" : [ /^1332444344/ ]}}")

Is there any workaround for this issue?

Thanks

I think it's the / s that are really causing the issue. You can't have a / before the start of string ( ^ ).

Java doesn't use / to indicate the start and end of regexes as other languages do. It uses " to mark the start and end, since regexes are written like any other string.

Remove the / , at least at the start of the regex; you may well want to remove the one at the end as well (depends on what you're actually trying to match).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM