首页 > 解决方案 > MongoDB 使用 $search 获取总计数聚合管道

问题描述

我必须使用 MongoDB Atlas 中的搜索索引以及普通浏览功能来实现搜索。这包括过滤、匹配、排序、跳过、限制(分页)。我制作了一个聚合管道来实现这一切。首先,我将搜索查询推送到我的管道,然后匹配、排序、然后跳过,最后是限制查询。

事情是这样的:

query = [];
query.push({
    $search: {
      index: 'default'
      text: {
        query: searchQuery
        path: {  }
      }
    }
  });
 query.push({
      $sort: sort,
    });
 query.push({
    $match: {
      type: match
    },

query.push({
  $skip: skip
});
query.push({
  $limit: perPage
});

let documents = await collection.aggregate(query);

到目前为止我得到的结果是正确的。但是,对于分页,我还想获取文档的总数。计数必须将“匹配”和“搜索查询”(如果有)考虑在内。我已经尝试过$facet,但它给出了错误$_internalSearchMongotRemote is not allowed to be used in a $facet stage

标签: node.jsmongodbexpressaggregation-frameworkmongodb-atlas-search

解决方案


因此,我看到此查询存在一些挑战。

  1. $sort可能不需要该阶段。默认情况下,所有搜索查询均按相关性得分排序。如果您需要根据其他标准进行排序,那么它可能是合适的。

  2. $match舞台可能不需要。大多数人在尝试匹配时正在寻找的是复合过滤器。正如您从文档中看到的那样, a 的filter行为类似于$match普通 MongoDB 中的 a。从我所在的位置来看,您的查询可能类似于:

如果您想快速计算返回的文档,则需要使用新的计数运算符。它在4.4.115.0.4集群上可用。你可以在这里阅读。


query = [];
query.push({
    $search: {
      index: 'default'
      "compound": {
      "filter": [{
        "text": {
          "query": match,
          "path": type
        }
      }],
      "must": [{
        "text": {
          "query": searchQuery,
          "path": { }
        }
      }]
    }, 
     "count": {
      "type": "total"
     }
   }
  });

query.push({
  $skip: skip
});

query.push({
  $limit: perPage
});

let documents = await collection.aggregate(query);



  [1]: https://docs.atlas.mongodb.com/reference/atlas-search/compound/#mongodb-data-filter
  [2]: https://docs.atlas.mongodb.com/reference/atlas-search/counting/#std-label-count-ref

推荐阅读