0

I'm trying to get the average of a field called Score that is inside an array of objects.

This is the sentence with which I tried to get it

db.classroom.aggregate([{$group : { _id : "$_id", puntaje : { $avg : "${userScore.score}" }}}])

The collection called Classroom is the following

{
        "_id" : ObjectId("56a0b43541c1375cd4e90b85"),
        "name" : "Desarrollo de Software",
        "comment" : "Salon destinado al Desarollo de Software",
        "code" : [
                {
                        "code" : "ABCDEF123456",
                        "user" : [
                                DBRef("user", 201309)
                        ]
                }
        ],
        "post" : [
                {
                        "post" : "Me gusta el salon :)",
                        "date" : ISODate("-292275055-05-16T16:47:03.192Z"),
                        "user" : DBRef("user", 201309)
                }
        ],
        "userScore" : [
                {
                        "score" : 4.5,
                        "user" : DBRef("user", 201309)
                }
        ]
}

Why the avg is always null ?

Community
  • 1
  • 1
DanyNsg
  • 355
  • 3
  • 10
  • 4
    Possible duplicate of [Average a Sub Document Field Across Documents in Mongo](http://stackoverflow.com/questions/19848860/average-a-sub-document-field-across-documents-in-mongo) or http://stackoverflow.com/questions/32234394/mongodb-sum-and-avg-of-sub-documents – BatScream Jan 21 '16 at 18:27
  • 1
    See @BatScream, you need to `$unwind` the data in `userScore.score` array first. – Alex Jan 21 '16 at 19:16

0 Answers0