SimplyCurious
SimplyCurious

Reputation: 3

Mongodb query to match words separated by space

I am implementing auto-complete feature using ajax, servlet and mongodb. Right now, I have implemented a logic which seems to be working partially

Example:

In database if i have following products

 1. Xbox Amazon
 2. Amazon xyz

When user enters ama, the result should contain both the products.But I am getting only Amazon xyz.

This is the logic I have written in java,

        DBCollection products = db.getCollection("Products");
        BasicDBObject dbObj = new BasicDBObject();
        dbObj.put("modelName",  Pattern.compile("^"+request.getParameter("startswith"),Pattern.CASE_INSENSITIVE));
        DBCursor cursor = products.find(dbObj);

Upvotes: 0

Views: 859

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

You can use \b (word boundary) in place of ^ for your case.

dbObj.put("modelName",  Pattern.compile("\\b"+request.getParameter("startswith"),Pattern.CASE_INSENSITIVE));

This will allow you to search on words that are not start of the strings and also does not match strings which contain ama as a part (Eg: Obama is not returned)

Upvotes: 2

Martin
Martin

Reputation: 5332

Use just the search string as pattern and it will work in this case. The reason why the pattern you created isn't working is that ^ means the string should be starting with the following pattern.

Upvotes: 0

Related Questions