Brian D
Brian D

Reputation: 1

Python / mongoDB Issue

I am learning how to use Python against mongoDB and am having difficulty understanding why I am unable to return a "$avg" aggregate value. I have a very small collection (9 records total) against which I appear to successfully use the "$match" aggregate function first to limit the documents (appear to pass along 3 documents further downstream in the pipeline). But for some reason the "$avg" value is not being calculated.

Here is the code I am using:

db.scores.aggregate( [
    { "$match" : { "test" : "quiz1" } },
    { "$group" : { "_id" : { "first" : "$first", "last" : "$last", "score" : "$score" }, "avgScore" : { "$avg" : "$score" } } }
    ])

And here is the output I receive:

{u'ok': 1.0, u'result': [{u'_id': {u'score': u'88', u'last': u'Black', u'first': u'Tom'}, u'avgScore': 0.0},
                         {u'_id': {u'score': u'87', u'last': u'Jones', u'first': u'Mary'}, u'avgScore': 0.0},
                         {u'_id': {u'score': u'89', u'last': u'Smith', u'first': u'Jay'}, u'avgScore': 0.0}]}

I don't understand why an "$avg" score is not returned for the 3 records that are making it to the "$group" statement in the pipeline.

Any thoughts/comments/suggestions would be greatly appreciated.

Thanks!

Upvotes: 0

Views: 30

Answers (1)

BatScream
BatScream

Reputation: 19700

The $avg operator works on numeric values and ignores non numeric values.

Returns the average value of the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key. $avg ignores non-numeric values.

Your results u'score': u'88' indicate that the score field is a of type String. You need to store them as Numbers.

Upvotes: 2

Related Questions