Docs Menu
Docs Home
/ / /
Node.js Driver

Run an Atlas Search Query

On this page

  • Overview
  • Sample Data
  • Run an Atlas Search Query
  • Atlas Search Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the Node.js driver to run Atlas Search queries on a collection. Atlas Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. Atlas Search indexes specify the behavior of the search and which fields to index.

The example in this guide uses the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

This section shows how to create an aggregation pipeline to run an Atlas Search query on a collection. In your array of pipeline stages, add the $search stage to specify the search criteria. Then, call the aggregate() method and pass your pipeline array as a parameter.

Tip

To learn more about aggregation operations, see the Aggregation guide.

Before running an Atlas Search query, you must create an Atlas Search index on your collection. To learn how to programmatically create an Atlas Search index, see the Atlas Search and Atlas Vector Search Indexes section of the Indexes guide.

This example runs an Atlas Search query by performing the following actions:

  • Creates a $search stage that instructs the driver to query for documents in which the title field contains the word "Alabama"

  • Creates a $project stage that instructs the driver to include the title field in the query results

  • Passes the pipeline stages to the aggregate() method and prints the results

const pipeline = [
{
$search: {
index: "default", // Replace with your search index name
text: {
query: "Alabama",
path: "title"
}
}
},
{
$project: {
title: 1
}
}
];
const cursor = collection.aggregate(pipeline);
for await (const document of cursor) {
console.log(document);
}
{
_id: new ObjectId('...'),
title: 'Alabama Moon'
}
{
_id: new ObjectId('...'),
title: 'Crazy in Alabama'
}
{
_id: new ObjectId('...'),
title: 'Sweet Home Alabama'
}

Tip

Node.js Driver Atlas Search Examples

To view more examples that use the Node.js driver to perform Atlas Search queries, see Atlas Search Tutorials in the Atlas documentation.

To learn more about Atlas Search, see Atlas Search in the Atlas documentation.

To learn more about the aggregate() method, see the API documentation.

Back

Run a Database Command