【发布时间】:2015-11-07 02:15:21
【问题描述】:
我正在尝试在 Flask 环境中使用 pymongo 从 MongoDB 返回一个简单的 JSON 结果。这就是我正在做的事情:
def myResults():
myCollection = db["my_data"]
results = list(myCollection.find({},{"ID":1,"Response":1,"_id":0}))
return jsonify(results=results)
当我这样做时,我得到以下结果。 FYI "ID" 基本上是一个虚构的唯一标识符。
{
"result": [
{
"ID": 1,
"Response": "A"
},
{
"ID": 4,
"Response": "B"
},
{
"ID": 3,
"Response": "A"
},
]
} // and so on...
我想汇总特定 ID 的所有响应并显示计数。我猜看起来像这样的东西(或者如果有更好的方法):
{
"result": [
{
"ID": 1,
"A": 2,
"B": 1,
"C": 5,
"Total": 8
},
{
"ID": 4,
"A": 0,
"B": 5,
"C": 18,
"Total": 23
},
{
"ID": 3,
"A": 12,
"B": 6,
"C": 8,
"Total": 26
},
]
}
StackOverflow 上有人推荐使用aggregate()。但它并不适合我。
allResults = surveyCollection.aggregate([
{"$unwind": result },
{"$group": {"_id": result.ID, "A": {"$sum": 1}, "B": {"$sum": 1}}},
{"$group": {"_id": None, "result": {"$push": {"ID": "$ID", "A": "$A", "B": "$B"}}}}
])
return jsonify(allResults)
我收到一个错误:AttributeError: 'list' object has no attribute 'ID'。
仅使用find() 或count() 就没有更简单的方法吗?
【问题讨论】:
-
Find() 返回一个游标,其中包含查询中收集的所有数据,它的简单命令,您只需对其进行迭代并获取信息。你这样做吗?
-
@Urbester 是的,我过去曾使用
find()来迭代并获取我想要的信息,但我想知道是否可以附加count()以解决上述问题。
标签: python mongodb mongodb-query pymongo aggregation-framework