How to use $near as a sort within a search query?

Hi,

I have a small (~38 megabytes) search index with a relatively simple query, however it is not performant with some queries with customer accounts that have a large amount of data indexed. The search will take longer than 60 seconds, which times out the HTTP request serving the frontend.

I’m trying to remove the $sort operation from the aggregation as recommended here: https://www.mongodb.com/docs/atlas/atlas-search/performance/query-performance/#-sort-aggregation-stage-usage

However, I’m a bit confused on how to use $near within the $search operation.

For context, I’m trying to sort based on a date field (createdAt), and the results should always be in descending order.

But I’m not sure if $near should be within a should clause or filter clause, and I’m also unsure how to use the pivot option to sort in a descending order:

const shopName = "test-inc";
const query = 'Smith';
const size = 25;
const page = 0;

const aggregation = [
    {
        $search: {
          index: "checks",
          compound: {
              $filter: {
                  {
                    phrase: {
                      query: shopName,
                      path: "shopName",
                    },
                  },
               },
              $should: [
                  {
                    text: {
                      query: searchTerm,
                      path: [
                          "firstName",
                          "lastName",
                          "phone",
                          "email",
                          "orderId",
                        ],
                    },
                  },
                  {
                    near: {
                      path: "createdAt",
                      origin: new Date(),
                      pivot: 86400000 * 7,
                      score: { boost: { value: 999 } },
                    },
                  },
                ],
          }
    },
    {
      $skip: parseInt(page) * parseInt(size),
    },
    {
      $limit: parseInt(size),
    },
    {
      $facet: {
         customers: [{
           $project: { 
             createdAt: 1, 
             name: 1,
             email: 1
           }
        }],
    },
    {
      $set: { meta: "$$SEARCH_META" },
    },
];

Hi @Dylan_Pierce ,

The following is relatively new and should help you here:

Regards,
Jason

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.