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

H. U. picture H. U. · Aug 12, 2015 · Viewed 9.9k times · Source

I am getting this TypeError when trying to access Bottle's rest API through Apache server, but it's working properly with Bottle's WSGI server.

Mongodb sample data:

 "_id" : ObjectId("55c4f21782f2811a08b7ddbb"),
 "TestName" : "TestName1",
 "Results" : [
     {
             "Test" : "abc",
             "Log" : "Log information"
     },
     {
             "Test" : "xyz",
             "Log" : "Log information"
     },
]

I want to fetch only those records/sub document where Results.Test="abc"

My Bottle API code:

@route('/TestSampleApi',method='GET')
def GetTestData():
    #request.json will have data passed in url
    pipe = [
            {"$match":{"Results": {"$elemMatch": {'Test':'abc'}}}}, 
                { "$unwind" :"$Results"},
                { "$match": { "Results.Test":'abc'}},
                { "$group" : { "_id" : "$_id", "Results" : { "$addToSet" : "$Results" } }}
            ]           
            res = collection.aggregate(pipeline=pipe)
            get_record=res['result']   #getting TypeError in this line 

    response.set_header('Content-Type',  'application/json')
    return dumps(get_record, indent=4)

Above code is working properly with curl -i GET "http://localhost:8080/TestSampleApi?Test=abc"
But not working with Apache: curl -i GET "http://HOST_NAME/TestSampleApi?Test=abc"

Answer

Bernie Hackett picture Bernie Hackett · Aug 14, 2015

In PyMongo 3 the aggregate method returns an iterable of result documents (an instance of CommandCursor), not a single document. You have to iterate the results, or alternatively turn them into a list with list(res).