How to perform LIKE searches in MongoDB with Java

<p>In order to perform searches just the SQL LIKE expression you need to provide a Regular Expression.</p>
<p>For example, supposing you have the following Document:</p>
<pre class=”brush:text”>{ “_id” : { “$oid” : “5541de4243875f38bcd22ea5”} , “title” : “The Da Vinci Code” , “author” : “Dan Brown” , “type” : “thriller” , “price” : 12 , “copies” : 10}</pre>
<p> Here is an example how to perform this search using the “Vinci” LIKE on the title:</p>
<pre class=”brush:java”>public static void main(String args[]) {
        try {
            // To connect to mongodb server
            MongoClient mongoClient = new MongoClient(“localhost”, 27017);

            DB db = mongoClient.getDB(“javaee7”);

            DBCollection coll = db.getCollection(“bookstore”);

            DBCursor cursor = null;

            BasicDBObject q = new BasicDBObject();
            q.put(“title”, java.util.regex.Pattern.compile(“Vinci”));
            cursor = coll.find(q);

            while (cursor.hasNext()) {
                DBObject obj = cursor.next();

                System.out.println(obj);

            }

            cursor.close();

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + “: ” + e.getMessage());
        }
    }</pre>
<p> </p>