如何在单个MongoDB查询结果中获取TotalCount和第一个文档?
有一个过滤器myFilter
用于获得有关XYZ
集合的一些见解。 现在,我需要运行三个查询,该查询具有相同的步骤以过滤文档
db.xyz.find(myFilter).sort(mySort1).limit(1) // get first item by sort #1
db.xyz.find(myFilter).sort(mySort2).limit(1) // get first item by sort #2
db.xyz.find(myFilter).count() // get total count
如何在单个查询或聚合中表达相同意图?
预期结果是
{
"item_1": {/* first doc by (myFilter & mySort1) *//},
"item_2": {/* first doc by (myFilter & mySort2) *//},
"totalCount": /* count of all by myFilter */
}
There is a filter myFilter
used to get some insights about the xyz
collection.
Now I need to run three queries having the same step for filtering the documents
db.xyz.find(myFilter).sort(mySort1).limit(1) // get first item by sort #1
db.xyz.find(myFilter).sort(mySort2).limit(1) // get first item by sort #2
db.xyz.find(myFilter).count() // get total count
How to express the same intention in a single query or aggregation?
Expected result is
{
"item_1": {/* first doc by (myFilter & mySort1) *//},
"item_2": {/* first doc by (myFilter & mySort2) *//},
"totalCount": /* count of all by myFilter */
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
$ facet
在一个查询中运行相同数据的几个管道:You can use
$facet
to run several pipelines on the same data at one query: