【问题标题】:TypeError: 'CommandCursor' object has no attribute '__getitem__'TypeError:“CommandCursor”对象没有属性“__getitem__”
【发布时间】:2015-11-04 09:37:59
【问题描述】:

我在尝试通过 Apache 服务器访问 Bottle 的 REST API 时遇到此类型错误,但它与 Bottle 的 WSGI 服务器 可以正常工作。

MongoDB示例数据:

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

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

我的 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"

【问题讨论】:

    标签: python apache mongodb pymongo bottle


    【解决方案1】:

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

    【讨论】:

    • 谢谢你 - 我一直想知道在我切换到新机器后出了什么问题。 result 字典现在是抽象的。 OP 可以使用get_record=res.next() 或类型转换为列表。
    猜你喜欢
    • 2012-12-04
    • 2012-10-15
    • 2014-01-16
    • 2017-02-27
    • 2018-01-28
    • 2014-06-10
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多