使用 python 计算 MongoDB 中的多个字段
Count multiple fields in MongoDB using python
我有这个简单的 mongodb 查询:
db.checks_reports_data_df8.find({"report_id": str(report["_id"])})
集合 checks_reports_data_df8
有一些字段,例如“success
”(可以是 0 或 1)和 is_listed
(可以是 0 或 1)。
我需要的是能够获得 success = 1
为 count_success
的所有字段以及 is_listed = 1
为 count_listed
的所有字段的计数。
最终结果类似于上面查询的所有结果 + count_success 和 count_listed
我想这可以使用聚合框架来完成。
编辑:
澄清一下,这是上面查询中的 return:
{'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'}
我需要的是 count_success = 3
(success=1 字段的总和)和 count_listed = 1
(is_listed=1 字段的总和)
像这样的东西应该有用。
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'}
}
}
])
我有这个简单的 mongodb 查询:
db.checks_reports_data_df8.find({"report_id": str(report["_id"])})
集合 checks_reports_data_df8
有一些字段,例如“success
”(可以是 0 或 1)和 is_listed
(可以是 0 或 1)。
我需要的是能够获得 success = 1
为 count_success
的所有字段以及 is_listed = 1
为 count_listed
的所有字段的计数。
最终结果类似于上面查询的所有结果 + count_success 和 count_listed
我想这可以使用聚合框架来完成。
编辑: 澄清一下,这是上面查询中的 return:
{'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'}
我需要的是 count_success = 3
(success=1 字段的总和)和 count_listed = 1
(is_listed=1 字段的总和)
像这样的东西应该有用。
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'}
}
}
])