SELECT name, COUNT(*)
FROM (
SELECT string_agg(name ORDER BY name) name
FROM mytable
GROUP BY startts, endts
ORDER BY name
) as names
GROUP BY name
ORDER BY name
我正在数据库中查询两次以查找文档总数。如何通过对数据库的单个查询来做到这一点?
答案 0 :(得分:2)
//you can use aggregation pipeline and $facet to combine two DB requests into one
//Actual Code output from windows Mongoshell/Command Line Interface(CLI)
> print("mongoDB",db.version())
mongoDB 4.2.6
> db.groups1.aggregate([
... {$facet:{
... "docCount":[
... {$group:{
... _id:null,
... count:{$sum:1}
... }
... }
... ],
... "allDocs":[
... {$match:{}}
... ]
... }
... }
... ]).pretty();
{
"docCount" : [
{
"_id" : null,
"count" : 4
}
],
"allDocs" : [
{
"_id" : ObjectId("5f817d142689512ef0bd3bd7"),
"uid" : 1,
"group_id" : "g1"
},
{
"_id" : ObjectId("5f817d142689512ef0bd3bd8"),
"uid" : 1,
"group_id" : "g2"
},
{
"_id" : ObjectId("5f817d142689512ef0bd3bd9"),
"uid" : 2,
"group_id" : "g2"
},
{
"_id" : ObjectId("5f817d142689512ef0bd3bd1"),
"uid" : 2,
"group_id" : "g3"
}
]
}
>
答案 1 :(得分:1)
使用$facet
聚合阶段将多个嵌套管道组合到您的主管道中。
这是上述想法的有效代码-
const countPipeline = [
{
$match: query
},
{
$group: {
_id: null,
count: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
count: '$count'
}
}
];
const postPipeline = [
{
$match: query
},
{
$skip: startIndex
},
{
$limit: noOfRecordsPerPage
},
{
$sort: {
createdAt: -1
}
}
];
const pipeline = [
{
$facet: {
posts: postPipeline,
count: countPipeline
}
}
];
const results = await Posts.aggreagate(pipeline).exec();