1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
===========
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/>` .
|