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

H. *_* U. 8 python apache mongodb pymongo bottle

当我试图通过Apache服务器访问Bottle的rest API时,我得到了这个TypeError ,但它与Bottle的WSGI服务器一起正常工作.

Mongodb样本数据:

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

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

我的瓶子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)
Run Code Online (Sandbox Code Playgroud)

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

Ber*_*ett 13

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

  • 谢谢你 - 我一直想知道在我换到一台新机器后出了什么问题。“结果”字典现在是抽象的。OP 可以使用 `get_record=res.next()` 或类型转换为列表。 (2认同)