1

This code gives me an error:

TypeError: 'CommandCursor' object has no attribute 'getitem'

However when my friend runs the same code on her computer, she doesn't get an error. I'm using an Intel Pentium CPU on Windows. I have MongoDB running (version 3.4), Python 2.7.13 :: Anaconda 4.3.1 (64-bit).

import json
import pymongo 
from bson import json_util
import re

FROM = "[email protected]"

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'
2
  • 1
    Can you provide the exact line of the error? Can you print only the aggregation command without ['result'][0]['recipients']? And which version of mongodb has your friend? Commented Mar 26, 2017 at 19:14
  • @moi-syme: Updated post with exact error message Commented Mar 30, 2017 at 11:44

1 Answer 1

1

Your friend must be running an old version of both MongoDB and PyMongo. Since PyMongo 3.0, running "aggregate" with PyMongo returns a cursor that you must iterate for results. Try this:

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']
Sign up to request clarification or add additional context in comments.

1 Comment

@a-jesse-jiryu-davis: I get a TypeError: list indices must be integers, not str

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.