问题
I'm having a collection which has 1000 records has a string column.
I'm using Jongo API for querying mongodb.
I need to find the matching records where column string starts with letter "AB" and ends with slash "/"
Need help on the query to query to select the same.
Thanks.
回答1:
I'm going to assume you know how to query using Regular Expressions in Jongo API and are just looking for the necessary regex to do so?
If so, this regex will find any string that begins 'AB' (case sensitive), is followed by any number of other characters and then ends with forward slash ('/'):
^AB.*\/$
^ - matches the start of the string
AB - matches the string 'AB' exactly
.* - matches any character ('.') any number of times ('*')
\/ - matches the literal character '/' (backslash is the escape character)
$ - matches the end of the string
If you're just getting started with regex, I highly recommend the Regex 101 website, it's a fantastic sandbox to test regex in and explains each step of your expression to make debugging much simpler.
回答2:
I have found out the solution and the following worked fine.
db.getCollection('employees').find({employeeName:{$regex: '^Raju.*\\/$'}})
db.getCollection('employees').find({employeeName:{$regex: '\/$'}})
getCollection().find("{employeeName:{$regex:
'^Raju.*\\\\/$'}}").as(Employee.class);
getCollection().find("{employeeName:{$regex: '\\/$'}}").as(Employee.class);
getCollection().find("{employeeName:#}",
Pattern.compile("\\/$")).as(Employee.class);
getCollection().find("{"Raju": {$regex: #}}", "\\/$").as(Employee.class);
map = new HashMap<>();
map.put("employeeName", Pattern.compile("\\/$"));
coll = getCollection().getDBCollection().find(new BasicDBObject(map));
回答3:
You could try this.
public List<Product> searchProducts(String keyword) {
MongoCursor<Product> cursor = collection.find("{name:#}", Pattern.compile(keyword + ".*")).as(Product.class);
List<Product> products = new ArrayList<Product>();
while (cursor.hasNext()) {
Product product = cursor.next();
products.add(product);
}
return products;
}
来源:https://stackoverflow.com/questions/39122664/regular-expression-to-find-string-starts-with-letter-and-ends-with-slash