node.js - 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
解决方案
因此,我看到此查询存在一些挑战。
$sort
可能不需要该阶段。默认情况下,所有搜索查询均按相关性得分排序。如果您需要根据其他标准进行排序,那么它可能是合适的。$match
舞台可能不需要。大多数人在尝试匹配时正在寻找的是复合过滤器。正如您从文档中看到的那样, a 的filter
行为类似于$match
普通 MongoDB 中的 a。从我所在的位置来看,您的查询可能类似于:
如果您想快速计算返回的文档,则需要使用新的计数运算符。它在4.4.11
和5.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
推荐阅读
- json - 用于高效 MongoDB 存储的字典或固定大小列表
- bash - 我们可以通过 Rest API 调用获取 Azure devops 现有的 PAT 令牌并通过 Rest API 重新生成 PAT 令牌吗?
- java - (已关闭)VS Code 中的 Gradle 导入失败
- c# - 如何检查文件下载 SSH.NET C#
- web-applications - iOS (iPad) PWA + SyncManager API
- f# - DRY自复制型
- html - 用 div 包装谷歌文档内容并转换为 html 文件
- java - 中缀到后缀表达式中的关联性规则
- mysql - 服务端开始累积查询,线程在信号量中等待已久
- java - 如何扩展 Jersey 的参数注释?