0

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!

1 Answer 1

2

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.

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

Comments

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.