gpt4 book ai didi

python - PyMongo 类型错误

转载 作者:可可西里 更新时间:2023-11-01 09:29:03 27 4
gpt4 key购买 nike

我有一个 python 脚本,我在其中使用 pymongo 聚合集合并在特定聚合的总和大于某个数字(在本例中为 30)时对它们执行某些操作。

  agg = collection.aggregate([{"$match":{"valid":1}}, {"$group": {"_id": {"createdby" : "$createdby" ,"addedtime" : "$addedtime", "empname" : "$empname"}, "count":{"$sum":1}}}])

cnt = 0
for eachAgg in agg:
print "eachAgg = ",eachAgg
if eachAgg['count'] >= 30:

当我运行这个脚本时,我得到了

  eachAgg = ok
Traceback (most recent call last):
File "test.py", line 33, in <module>
if eachAgg['count'] >= 30:
TypeError: string indices must be integers

我不明白 $sum 聚合为什么不是整数。

最佳答案

agg: 返回带有聚合结果的更详细的字典,即:

    { 
u'ok': 1.0,
u'waitedMS': 0L,
u'result': [<your actual aggregation result>]
}

这就是你得到 TypeError: string indices must be integers 的原因,因为你迭代了字典中的键 (for eachAgg in agg) ,其中键是字符串并且字符串索引必须是整数。

真正的数据结果在agg['result']中,试试:

for eachAgg in agg['result']:
if eachAgg['count'] >= 30:
....

关于python - PyMongo 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41098002/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com