【发布时间】:2014-10-29 05:52:42
【问题描述】:
我正在尝试在 mongodb 中实现嵌套组查询,但在尝试添加外部组时遇到了困难。给定以下(简化的)数据文档:
{
"timestamp" : ISODate(),
"category" : "movies",
"term" : "my movie"
}
我正在尝试获得所有类别的列表,并且在类别中应该有最多的术语。我希望我的输出是这样的:
[
{ 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 } ... ]
},
]
我的“内组”如下图,将获得所有类别的前5名:
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 }
我将如何实施“外部小组”?
此外,有时上述聚合]ion 会返回空值(并非所有文档都有术语值)。如何忽略空值?
提前致谢
【问题讨论】:
标签: mongodb mongodb-query