MongoDB 嵌套组? [英] MongoDB nested group?
问题描述
我正在尝试在 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 嵌套组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!