2013-05-20 40 views
0

我在MongoDB中有以下集合。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 } 

我想算的文章(articulos),最大等级(calificacion)由作者(作者日期)的数量。

xxxx1有5 XXXX2的2个物品已与5

1页的文章(我不知道什么是最高等级)

我已经试过这样:

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

但我只得到最高等级的作者。我可以使用Aggregation Framework吗?

回答

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 
} 

感谢, 琳达

+0

喔谢谢!!!!有用!!!!我在学习mongo,所以我需要了解我可以如何进行简单查询。 – drsromero