MongoDB和聚合框架

时间:2013-05-20 16:35:07

标签: mongodb aggregation-framework

我在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 }

我想用作者(autor)计算最高等级(calificacion)的文章(articulos)的数量。

xxxx1有2篇文章,等级5 xxxx2有1篇文章,等级5

(我不知道什么是最高等级)

我试过这个:

db.ejemplo.aggregate([
    {$group:{_id: "$autor" , calificacion:{$max:"$calificacion" }}} 
])

但我只获得最高分的作者。我可以用聚合框架吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的聚合操作:

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" },
    }}
])

结果是这样的:

{
    "result" : [
        {
            "_id" : "xxxx1",
            "calificacion" : 5,
            "articulos" : 2
        },
        {
            "_id" : "xxxx2",
            "calificacion" : 5,
            "articulos" : 1
        }
    ],
    "ok" : 1
}

谢谢, 琳达