0

I have this simple mongodb query:

db.checks_reports_data_df8.find({"report_id": str(report["_id"])})

The collection checks_reports_data_df8 is having some fields like "success" (can be 0 or 1) and is_listed (can be 0 or 1).

What I need is to be able to get the counts of all fields where success = 1 as count_success and all fields where is_listed = 1 as count_listed. The final result will be something like all the results from the query above + count_success and count_listed

I suppose that this can be done using the aggregation framework.

EDIT: To clarify, here is the return from the query above:

{'is_listed': 0, 'success': 1, '_id': ObjectId('54dca9920e13a771a44433d4'), 'report_id': u'54dca97758a5d3a37c8b4567'}
{'is_listed': 0, 'success': 1, '_id': ObjectId('54dca9920e13a771a44433a3'), 'report_id': u'54dca97758a5d3a37c8b4567'}
{'is_listed': 1, 'success': 1, '_id': ObjectId('54dca9920e13a771a44433c2'), 'report_id': u'54dca97758a5d3a37c8b4567'}

What I need, is to have count_success = 3 (the sum of the success=1 fields) and count_listed = 1 (the sum of the is_listed=1 fields)

1
  • 1
    For clarity, could you post a sample document and your expected output? Commented Feb 12, 2015 at 20:12

1 Answer 1

1

Something like this should work.

db.checks_reports_data_df8.aggregate([
        {
                '$match' : 
                    {
                        "report_id": str(report["_id"])
                    }
        },
        {
            '$group' : 
                {
                    '_id': '$report_id',
                    count_success :{'$sum': '$success'},
                    count_is_listed:{'$sum':'$is_listed'}
                }
        }
])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.