0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ohh Thank you!!!! It works!!!! I'm learning mongo so I need to understand how I can do simples queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.