Reputation: 311
I have the following collection in mongodb.
{ "_id" : ObjectId("519a35ee8f2ceda43f42add5"), "articulo" : "Sobre mongodb", "autor" : "xxxx1", "calificacion" : 3 }
{ "_id" : ObjectId("519a360b8f2ceda43f42add6"), "articulo" : "Aggregation framework", "autor" : "xxxx1", "calificacion" : 5 }
{ "_id" : ObjectId("519a361b8f2ceda43f42add7"), "articulo" : "Sobre journal", "autor" : "xxxx2", "calificacion" : 4 }
{ "_id" : ObjectId("519a362e8f2ceda43f42add8"), "articulo" : "Manipulando datos", "autor" : "xxxx1", "calificacion" : 2 }
{ "_id" : ObjectId("519a36418f2ceda43f42add9"), "articulo" : "MongoDB for dba", "autor" : "xxxx2", "calificacion" : 5 }
{ "_id" : ObjectId("519a4aa18f2ceda43f42adda"), "articulo" : "ejemplo2", "autor" : "xxxx1", "calificacion" : 5 }
I want to count the number of the articles (articulos) with max grade (calificacion) by author(autor).
xxxx1 has 2 articles with grade of 5 xxxx2 has 1 articles with grade of 5
(I don't know what's the max grade)
I've tried this:
db.ejemplo.aggregate([
{$group:{_id: "$autor" , calificacion:{$max:"$calificacion" }}}
])
but I only get the authors with max grade. Could I do it with Aggregation Framework?
Upvotes: 0
Views: 131
Reputation: 1056
You can try the aggregation operation like this:
db.ejemplo.aggregate([
{ $group : { _id : { autor : "$autor",
calificacion : "$calificacion" },
articulos : { $sum : 1 },
}},
{ $sort : { "_id.calificacion" : -1 }},
{ $group : { _id : "$_id.autor",
calificacion : { $first : "$_id.calificacion" },
articulos : { $first : "$articulos" },
}}
])
And the result is like this:
{
"result" : [
{
"_id" : "xxxx1",
"calificacion" : 5,
"articulos" : 2
},
{
"_id" : "xxxx2",
"calificacion" : 5,
"articulos" : 1
}
],
"ok" : 1
}
Thanks, Linda
Upvotes: 2