Text Search

Use the $text operator to perform text searches on fields which have a text index.

To create a text index on a collection, pass a document containing the name of the field to be indexed with the value ‘text’ to the createIndex() method.

function createTextIndex(db, callback) {
  // Get the restaurants collection
  const collection = db.collection('restaurants');
  // Create the index
  collection.createIndex(
    { name : "text" }, function(err, result) {
    console.log(result);
    callback(result);
  });
};


const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err, client) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  const db = client.db(dbName);
  createTextIndex(db, function() {
    client.close();
  });
});

The following example assumes that a database called test has a collection called restaurants, with a text index on the name field. A sample dataset is available for download.

function findDocuments(db, callback) {
  // Get the documents collection
  const collection = db.collection('restaurants');
  // Find some documents
  collection.find({ '$text': {'$search' : 'Garden' } } ).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
}

// use the findDocuments() function
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err, client) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  const db = client.db(dbName);

  findDocuments(db, function() {
    client.close();
  });
});

For more information about the $text operator and its options, see the manual entry.

On this page