===========
Text Search
===========

Use the :manual:`$text </reference/operator/query/text/>`
operator to perform text searches on fields which have a
:manual:`text index </core/index-text/>` .

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.

.. code-block:: js

   const { MongoClient } = require('mongodb');
   
   // Connection URL
   const url = 'mongodb://localhost:27017';
   
   // Create a new MongoClient
   const client = new MongoClient(url);

   async function main(client) {
     const collection = client.db('myproject').collection('restaurants');
     const results = await collection.createIndex({ name : "text" });
     console.log(results);
   }

   // Function to connect to the server and run your code
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');

       await main(client);
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

The following example assumes that a database called ``test`` has a
collection called ``restaurants``\ , with a text index on the ``name`` field.

.. raw::html

    <!-- A `sample dataset <https://docs.mongodb.org/getting-started/node/import-data/>`_ is available for download. -->
    <!-- This link redirects to "http://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/". We should fix this -->

.. code-block:: js

   async function main(client) {
     const collection = client.db('myproject').collection('restaurants');
     const docs = await collection.find({ '$text': {'$search' : 'Garden' } } ).toArray();
     console.log("Found the following records");
     console.log(docs);
   }

For more information about the ``$text`` operator and its options, see the
:manual:`manual entry </reference/operator/query/text/>` .
