MongoDB聚合和项目总数的结果

我使用下面的查询使用db.collection.aggregate()。 我得到的结果很好,其中投影字段正如下面指定的。 我也想得到符合这个标准的文件总数。

db.collection.aggregate([ { $match: { "age": {"$gte": 20, "$lte": 30}} }, { $lookup: { from: "photos", localField: "post_id", foreignField: "post_id", as: "photos"} }, { $project: { "title": 1, "photos.path": 1, "age": 1, "city": 1, "location": 1, "post_id": 1, "score": { "$meta": "textScore"} } }, { $sort: { score: { $meta: "textScore" } } }, { $skip: 0 }, { $limit: 30 }, ]) 

经过一番研究,我发现我需要添加下面的选项:

  { $group: { _id: null, count: { $sum: 1 } } } 

但是,这个补充,我现在得到这个作为回应:

  { "_id" : null, "count" : 400 } 

伯爵是正确的,但我想要投射的领域不再存在。 有一种方法来获得计数,我想在一个结果项目的领域? 或者我必须运行两个单独的查询,一个用于计数,一个用于我想要投影的字段?

是的,可以用$ push来访问分组的文档

将此添加到您的聚合pipe道

{$ group:{_id:{“title”:“$ title”,“age”:“$ age”,“city”:“$ city”,“location”:“$ location”,“post_id”:“$ post_id“,”score“:”$ score“},count:{$ sum:1}}})