MongoDB supports query operations that perform a text search of string content. To perform text search, MongoDB uses a text index and the $text query operator.

The Java driver provides the Filters.text() helper to facilitate the creation of text search query filters.

Prerequisites

  • The example below requires a restaurants collection in the test database. To create and populate the collection, follow the directions in github.

  • Include the following import statements:

import com.mongodb.Block;
import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import com.mongodb.client.model.*;
import org.bson.Document;
  • Include the following code which the examples in the tutorials will use to print the results of the aggregation:
Block<Document> printBlock = new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document.toJson());
    }
};

Connect to a MongoDB Deployment

Connect to a MongoDB deployment and declare and define a MongoDatabase and a MongoCollection instances.

For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port 27017 and define database to refer to the test database and collection to refer to the restaurants collection:

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("restaurants");

For additional information on connecting to MongoDB, see Connect to MongoDB.

Create the text Index

To create a text index, use the Indexes.text static helper to create a specification for a text index and pass to MongoCollection.createIndex() method.

The following example creates a text index on the name field for the restaurants collection.

collection.createIndex(Indexes.text("name"), new SingleResultCallback<String>() {
    @Override
    public void onResult(final String result, final Throwable t) {
        System.out.println("Operation Finished!");
    }
});

To perform text search, use the Filters.text() helper to specify the text search query filter.

For example, the following code performs a text search on the name field for the word "bakery" or "coffee".

collection.countDocuments(Filters.text("bakery coffee"), new SingleResultCallback<Long>()  {
    @Override
    public void onResult(final Long count, final Throwable t) {
        System.out.println("Text search matches: " +count);
    }
});

The example should print the following output:

Text search matches: 2

For more information on the text search, see $text operator.

Text Score

For each matching document, text search assigns a score, representing the relevance of a document to the specified text search query filter. To return and sort by score, use the $meta operator in the projection document and the sort expression.

collection.find(Filters.text("bakery cafe"))
                       .projection(Projections.metaTextScore("score"))
                       .sort(Sorts.metaTextScore("score"))
          .forEach(printBlock, new SingleResultCallback<Void>() {
              @Override
              public void onResult(final Void result, final Throwable t) {
                  System.out.println("Operation Finished!");
              }
          });

Specify a Text Search Option

The Filters.text() helper can accept various text search options. The Java driver provides TextSearchOptions class to specify these options.

For example, the following text search specifies the text search language option when performing text search for the word cafe:

collection.countDocuments(Filters.text("cafe",
      new TextSearchOptions().language("english")),
      new SingleResultCallback<Long>()  {
            @Override
            public void onResult(final Long count, final Throwable t) {
                System.out.println("Text search matches: " +count);
            }
});

The example should print the following output:

Text search matches: 1

For more information about text search see the following sections in the MongoDB Server Manual: