Javascript 检索包含与查询匹配的文档子集和匹配总数的文档
如何查询集合以检索与查询匹配的有限数量的文档以及同时与所述查询匹配的文档数量 我在寻找这样的结果:Javascript 检索包含与查询匹配的文档子集和匹配总数的文档,javascript,node.js,mongodb,mongoose,aggregation-framework,Javascript,Node.js,Mongodb,Mongoose,Aggregation Framework,如何查询集合以检索与查询匹配的有限数量的文档以及同时与所述查询匹配的文档数量 我在寻找这样的结果: { result : [ { _id:null, total:734, //there are 734 documents matching the query page:[ //limited to 3 {_id:"...", someValue:30000}
{
result : [
{
_id:null,
total:734, //there are 734 documents matching the query
page:[ //limited to 3
{_id:"...", someValue:30000}
{_id:"...", someValue:30400}
{_id:"...", someValue:31900}
]
}
]
}
我试图将其用于分页目的。为了进一步解释,您似乎试图使用聚合框架实现总结果计数的“分页”。这不是一个好主意,因此我将向您说明原因:
db.collection.aggregate([
// Some query to match results
{ "$match": { /* some query */ } },
// Then group to get the count -- OOPS!
{ "$group": {
"_id": null,
"page": { "$push": /* the documents */ }, // essentially the problem
"total": { "$sum": 1 }
}},
// Then unwind -- oh dear!
{ "$unwind": "$page" },
// Then skip and limit
{ "$skip": 100 },
{ "$limit": 25 }
// And group back again :-<
{ "$group": {
"_id": null,
"total": { "$first": "$total" },
"page": { "$push": "$page" }
}}
])
理想情况下,您确实应该查看范围查询,而不是使用“跳过”和“限制”,或者通常只查找仅向前分页的最后一个“可见”值“大于”
如果必须对查询结果使用聚合框架,则可以,但也可以采用相同的方法。尝试获取总计数,然后“翻页”出结果是非常糟糕的。看起来您需要对结果进行某种“统计”,例如总计数,然后是有限的“当前页面”。您最好的方法是使用多个查询执行此操作,并操纵对象返回。@NeilLunn当前,我首先获取计数,然后执行分页请求,但我相信这两个操作应该在一个查询中就可以完成。提供的答案中是否有什么东西不能回答您的问题?没有,只是在根据您的答案实施和测试通用解决方案之前,我在其他项目中做得太过火了。击掌!
// Avoiding the indentation creep
var queryDoc = {};
async.waterfall(
[
function(callback) {
Model.count(queryDoc,function(err,count) {
callback(err,count);
}
},
function(count,callback) {
var query = Model.find(queryDoc);
query.skip(100).limit(25).exec(function(err,page) {
callback(err,{ "total": count, "page": page });
});
}
],
function(err, result) {
if (err) throw err; // or handle
console.log( result ); // or res.send or whatever
}
);