我试图在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 }
我将如何实施'外部组'?
另外,有时上面的聚合]离子返回一个空值(并非所有文档都有一个术语值)。我如何忽略空值?
提前致谢
答案 0 :(得分:19)
在这种情况下,您需要两组。第一组生成一个文档流,每个术语和类别包含一个文档:
{ $group : {
_id : {
category: "$category",
term: "$term",
},
total: { $sum : 1 }
}
}
然后第二个组将所有具有相同术语的文档合并为一个,使用$push运算符将类别合并到一个数组中:
{ $group : {
_id : "$_id.category",
terms: {
$push: {
term:"$_id.term",
total:"$total"
}
}
}
}
答案 1 :(得分:0)
查询:
function findLongestWordLength(str) {
let longestWord = "";
let currentWord = "";
//Move through the string letter-by-letter
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) === " ") { //If we're at a space character
if (currentWord.length > longestWord.length) longestWord = currentWord; //Check if that word was the longest
currentWord = ""; //Reset the current word
} else {
currentWord += str.charAt(i); //Not at a space character, still building the current word
}
}
if (currentWord > longestWord) longestWord = currentWord; //End of string - check current word once more
return longestWord;
}
const longest = findLongestWordLength("The quick brown fox jumped over the lazy dog");
console.log(longest);
响应:
db.getCollection('orders').aggregate([
{$match:{
tipo: {$regex:"[A-Z]+"}
}
},
{$group:
{
_id:{
codigo:"1",
tipo:"$tipo",
},
total:{$sum:1}
}
},
{$group:
{
_id:"$_id.codigo",
tipos:
{
$push:
{
tipo:"$_id.tipo",
total:"$total"
}
},
totalGeneral:{$sum:"$total"}
}
}
]);
}