我试图存储输入到管道中的记录总数,以便在以后的计算中使用该数目.如何获取输入数量,然后展开,然后在以后的计算中使用输入数量?
I'm trying to store the total number of records input to the pipe so I can use the number in a later calculation. How do I grab the number of inputs, then unwind, then use the number of inputs later in my calcs?
我可以通过以下方式获取电话号码:
I can get the number by doing this:
db.articles.aggregate([ { $count: "totalArticles" } ]}我可以通过执行以下操作获得所需的其余数据:
I can get the rest of the data I want by doing this:
db.articles.aggregate([ { $unwind: "$concepts" }, { $group: { _id: "$concepts.text", count: { $sum: 1 }, average: { $avg: "$concepts.relevance" }, } } ])我真正想做的是:
db.articles.aggregate([ { $count: "totalArticles" }, { $unwind: "$concepts" }, { $group: { _id: "$concepts.text", count: { $sum: 1 }, average: { $avg: "$concepts.relevance" } } }, { $project: { count: "$count", percent: { $divide: [ "$count", "$totalArticles" ] } } }, { $sort: { count: -1 } } ])推荐答案
您可以使用以下聚合查询.
You can use below aggregation query.
初始$group计算总计数,而$push将概念字段转换为数组字段. $$ROOT访问整个文档.
Initial $group to calculate the total count while $push the concepts field into array field. $$ROOT to access the whole doc.
在下一个$group中保留文章总数.
Retain the total articles count in next $group.
一切都保持原样.
db.articles.aggregate([ {"$group":{ "_id":null, "totalArticles":{"$sum":1}, "concepts":{"$push":"$$ROOT.concepts"} }}, {"$unwind":"$concepts"}, {"$group":{ "_id":"$concepts.text", "totalArticles":{"$first":"$totalArticles"}, "count":{"$sum":1}, "average":{"$avg":"$concepts.relevance"} }}, {"$project":{ "count": "$count", "percent": { "$divide": [ "$count", "$totalArticles" ] } } }, {"$sort": {"count": -1}} ])$facets也是一种选择,您可以在两个单独的管道中进行两个查询,然后合并以继续其余阶段.
$facets is also an option where you can two queries in two separate pipeline followed by merge to continue with rest of stages.
更多推荐
Mongodb:在组之后的聚合中使用记录计数
发布评论