Question

I am using MongoDB with Java Driver (http://tinyurl.com/dyjxz8k). In my application I want it to be possible to give results that contains a substring of the users search-term. The method looks like this:

*searchlabel = the name of a field *searchTerm = the users searchword

 private void dbSearch(String searchlabel, String searchTerm){
    if(searchTerm != null && (searchTerm.length() > 0)){

        DBCollection coll = db.getCollection("MediaCollection");
        BasicDBObject query = new BasicDBObject(searchlabel, searchTerm);
        DBCursor cursor = coll.find();
        cursor = coll.find(query);

        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next());
                //view.showResult(cursor.next());
            }
        } finally {
            cursor.close();
        }

    }
}

Does anybody have any idea about how I can solve this? Thanks in advance =) And a small additional question: How can I handle the DBObjects according to presentation in (a JLabel in) view?

Was it helpful?

Solution

For text-searching in Mongo, there are two options:

  • $regex operator - however unless you have a simple prefix regexp, queries won't use an index, and will result in a full scan, which usually is slow
  • In Mongo 2.4, a new text index has been introduced. A text query will split your query into words, and do an or-search for documents including any of the words. Text indexes also eliminate some stop-words and have simple stemming for some languages (see the docs).

If you are looking for a more advanced full-text search engine, with more powerful tokenising, stemming, autocomplete etc., maybe a better fit would be e.g. ElasticSearch.

OTHER TIPS

I use this method in the mongo console to search with a regular expression in JavaScript:

// My name to search for
var searchWord = "alex";

// Construct a query with a simple /^alex$/i regex
var query = {};
query.animalName = new RegExp("^"+searchWord+"$","i");

// Perform find operation
var lionsNamedAlex = db.lions.find(query);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top