MongoDB 嵌套组?

编程入门 行业动态 更新时间:2024-10-25 00:26:24
本文介绍了MongoDB 嵌套组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 mongodb 中实现嵌套组查询,但在尝试添加外部组时遇到了困难.鉴于以下(简化的)数据文档:

{时间戳":ISODate(),类别":电影","term" : "我的电影"}

我正在尝试获得所有类别的列表,并且在类别中应该有最多的术语.我希望我的输出是这样的:

[{ 类别:电影",条款:[ { 术语:电影 1",总计:5000 },{ 术语:电影 2",总计:200 } ... ]},{ 类别:体育",条款:[ { 术语:足球 1",总计:4000 },{ 术语:网球 2",总计:250 } ... ]},]

我的内部组"如下图所示,将获得所有类别的前 5 名:

db.collection.aggregate([{ $match : { "timestamp": { $gt: ISODate("2014-08-27") } } },{ $group : { _id : "$term", total : { $sum : 1 } } },{ $sort : { total : -1 } },{ $limit: 5 }]);//输出:{_id":电影 1",总计":943 }{_id":电影 2",总计":752 }

我将如何实施外部团体"?

此外,有时上述聚合]ion 会返回空值(并非所有文档都具有 term 值).如何忽略空值?

提前致谢

解决方案

在这种情况下,您将需要两个组.第一组生成一个文档流,每个术语和类别一个文档:

{ $group : {_ID : {类别:$类别",术语:$term",},总计:{ $sum :1}}}

然后,第二组将使用 $push 运算符将类别合并到一个数组中:

{ $group : {_id : "$_id.category",条款:{$推:{term:"$_id.term",总计:$总计"}}}}

I'm trying to implement a nested group query in mongodb and I'm getting stuck trying to add the outer group by. Given the below (simplified) data document:

{ "timestamp" : ISODate(), "category" : "movies", "term" : "my movie" }

I'm trying to achieve a list of all categories and within the categories there should be the top number of terms. I would like my output something like this:

[ { category: "movies", terms: [ { term: "movie 1", total: 5000 }, { term: "movie 2", total: 200 } ... ] }, { category: "sports", terms: [ { term: "football 1", total: 4000 }, { term: "tennis 2", total: 250 } ... ] }, ]

My 'inner group' is as shown below, and will get the top 5 for all categories:

db.collection.aggregate([ { $match : { "timestamp": { $gt: ISODate("2014-08-27") } } }, { $group : { _id : "$term", total : { $sum : 1 } } }, { $sort : { total : -1 } }, { $limit: 5 } ]); // Outputs: { "_id" : "movie 1", "total" : 943 } { "_id" : "movie 2", "total" : 752 }

How would I go about implementing the 'outer group'?

Additionally sometimes the above aggregate]ion returns a null value (not all documents have a term value). How do I go about ignoring the null values?

thanks in advance

解决方案

You will need two groups in this case. The first group generates a stream of documents with one document per term and category:

{ $group : { _id : { category: "$category", term: "$term", }, total: { $sum : 1 } } }

A second group will then merge all documents with the same term into one, using the $push operator to merge the categories into an array:

{ $group : { _id : "$_id.category", terms: { $push: { term:"$_id.term", total:"$total" } } } }

更多推荐

MongoDB 嵌套组?

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

发布评论

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

>www.elefans.com

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