[英]Multiples group aggregate in mongodb
可以說我有這樣的書籍收藏:
{author:"john", category:"action", title:"foobar200"},
{author:"peter", category:"scifi" , title:"42test"},
{author:"peter", category:"novel", title:"whatever_t"},
{author:"jane", category:"novel", title:"the return"},
{author:"john", category:"action", title:"extreme test"},
{author:"peter", category:"scifi", title:"such title"},
{author:"jane", category:"action", title:"super book "}
我想做類似的查詢:
SELECT author,category, count(*) FROM books GROUP BY category, author
==>結果:
john -> action -> 2
john -> novel -> 0
john -> scifi -> 0
jane -> action -> 1
etc...
我最近去過的解決方案是這樣的:
db.books.aggregate(
{
$match: {category:"action"}
},
{
$group: { _id: '$author', result: { $sum: 1 } }
}
);
==>結果
{ "_id" : "jane", "result" : 1 }
{ "_id" : "john", "result" : 2 }
{ "_id" : "peter", "result" : 0 }
但是我不明白如何執行帶有類別的第二個“分組依據”。
做這個的最好方式是什么 ?
謝謝
您可以在$group
使用的_id
包含多個字段,以提供多字段分組:
db.books.aggregate([
{$group: {
_id: {category: '$category', author: '$author'},
result: {$sum: 1}
}}
])
結果:
{
"_id" : {
"category" : "action",
"author" : "jane"
},
"result" : 1
},
{
"_id" : {
"category" : "novel",
"author" : "jane"
},
"result" : 1
},
{
"_id" : {
"category" : "novel",
"author" : "peter"
},
"result" : 1
},
{
"_id" : {
"category" : "scifi",
"author" : "peter"
},
"result" : 2
},
{
"_id" : {
"category" : "action",
"author" : "john"
},
"result" : 2
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.