Python MongoDB聚合错误

时间:2017-03-26 16:55:34

标签: python mongodb aggregation-framework pymongo

此代码给出了一个错误:

TypeError:'CommandCursor'对象没有属性' getitem '

然而,当我的朋友在她的计算机上运行相同的代码时,她没有收到错误。我在Windows上使用Intel Pentium CPU。我有MongoDB运行(版本3.4),Python 2.7.13 :: Anaconda 4.3.1(64位)。

import json
import pymongo 
from bson import json_util
import re

FROM = "kenneth.lay@enron.com"

client = pymongo.MongoClient()
db = client.enron    
mbox = db.mbox

//Get the recipient lists for each message

recipients_per_message = db.mbox.aggregate([
{"$match" : {"From" : re.compile(r".*{0}.*".format(FROM), re.IGNORECASE)}}, 
{"$project" : {"From" : 1, "To" : 1} }, 
{"$group" : {"_id" : "$From", "recipients" : {"$addToSet" : "$To" } } }                    
])['result'][0]['recipients']

//The exact Error was:
TypeError Traceback (most recent call last) 
19 {"$project" : {"From" : 1, "To" : 1} },   
20 {"$group" : {"_id" : "$From", "recipients" : {"$addToSet":"$To" }}}  
---> 21 ])['result'][0]['recipients'] 
TypeError: 'CommandCursor' object has no attribute 'getitem'

1 个答案:

答案 0 :(得分:1)

你的朋友必须运行MongoDB和PyMongo的旧版本。从PyMongo 3.0开始,运行"聚合"使用PyMongo返回一个必须迭代结果的游标。试试这个:

results = list(db.mbox.aggregate([
    {"$match" : {"From" : re.compile(r".*{0}.*".format(FROM), re.IGNORECASE)}}, 
    {"$project" : {"From" : 1, "To" : 1} }, 
    {"$group" : {"_id" : "$From", "recipients" : {"$addToSet" : "$To" } } }                    
]))
recipients_per_message = results['result'][0]['recipients']