Mongodb:在组之后的聚合中使用记录计数

编程入门 行业动态 更新时间:2024-10-28 22:29:21
本文介绍了Mongodb:在组之后的聚合中使用记录计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图存储输入到管道中的记录总数,以便在以后的计算中使用该数目.如何获取输入数量,然后展开,然后在以后的计算中使用输入数量?

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:在组之后的聚合中使用记录计数

本文发布于:2023-11-22 17:17:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!