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

时间:2015-08-12 00:10:15

标签: python apache mongodb pymongo bottle

我在尝试通过 Apache 服务器访问Bottle的其余API时遇到此类型错误,但它与 Bottle的WSGI服务器< / strong>即可。

Mongodb样本数据:

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

我想只获取那些记录/子文档,其中Results.Test =&#34; abc&#34;

My Bottle API代码:

@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)

以上代码正常使用 curl -i GET "http://localhost:8080/TestSampleApi?Test=abc"
但不使用Apache:     curl -i GET "http://HOST_NAME/TestSampleApi?Test=abc"

1 个答案:

答案 0 :(得分:13)

在PyMongo 3中,aggregate方法返回一个可迭代的结果文档(CommandCursor的一个实例),而不是单个文档。您必须迭代结果,或者将它们转换为带有列表(res)的列表。