Search Fundamentals / Creating an Atlas Search Query

Code Recap: Creating an Atlas Search Query

Create an Atlas Search query using $search

In the following example, the compound operator is used with a must clause inside the $search stage to find movies based on keywords in the title and plot fields and that fall into a specific date range. It uses the $limit stage to show only the top 10 results and the $project stage to only return the title, plot, and released fields.

db.movies.aggregate([
  {
    $search: {
      index: "titlePlotReleasedIndex",
      compound: {
        must: [
          {
            text: {
              query: "investigation",
              path: ["title", "plot"],
              fuzzy: {}
            }
          },
          {
            range: {
              path: "released",
              gte: ISODate("2000-01-01T00:00:00Z"),
              lte: ISODate("2010-12-31T23:59:59Z")
            }
          }
        ]
      }
    }
  },
  {
    $limit: 10
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      released: 1
    }
  }
]);