2014-02-07 32 views
-1

是否可以将key:value附加到MongoDB游标?如何将key:value附加到MongoDB游标?

我尝试这样做:

cursor = collection.find(query,projection) 
cursor['my_message'] = "value here" # trying to add key:value here 

但它似乎没有工作(500)。

在更多情况下,这个工程:

dbname = 'my_db' 
db = connection[dbname] 
collection = db.my_collection 
query = {'key_1': my_var} 
projection = {'key_2':1} 
cursor = collection.find(query,projection) 
response.content_type = 'application/json' 
return dumps(cursor) 

这不:

dbname = 'my_db' 
db = connection[dbname] 
collection = db.my_collection 
query = {'key_1': my_var} 
projection = {'key_2':1} 
cursor = collection.find(query,projection) 
cursor['my_message'] = "value here" # trying to add key:value here 
response.content_type = 'application/json' 
return dumps(cursor) 

编辑:而只是为了形象化被成功返回什么(不含附加价值),它是这样的:

[{ document_1 },{ document_2 },{ document_3 }] 

我希望它看起来是这样的:

["my_message":"value here",{ document_1 },{ document_2 },{ document_3 }] 

编辑:我尝试以下作为一种替代,也得到了500

entries = [] 
cursor = collection.find(query,projection) 
for entry in cursor: 
    entries.append(entry) 
entries['my_message'] = "value here" 
response.content_type = 'application/json' 
return dumps(entries) 
+2

为什么不把它分成2:'result = {my_message:'value here,data:cursor}'? – WiredPrairie

+0

这是可行的(用逗号分隔键),但它意味着在前端数组迭代时,而不是使用'$ .each(results ...',我使用'$ .each(results.data'。I 'd仍然有兴趣知道为什么我不能直接追加到游标(我假设这是一个字典?)。 – user1063287

+0

条目是一个列表,而不是一个散列 - 所以当你调用'转储时它会返回一个列表''''我想象一下,它不会在列表中包含你在运行时放在对象上的键值 – WiredPrairie

回答

1

真的,WiredPrarie右一开始回答了这个给你,每个人都说同样的话。

我们知道你想要做什么。您希望您的序列化响应可以发回一些您想要放入的信息,然后输出结果集。我还假定你想使用这些结果和你的其他数据,可能会加载到一些JavaScript处理商店。

我从来没有见过任何东西,没想到某种结构,如:

{ 
    "result": "ok", 
    "meta": [{ akey: "avalue"}, {bkey: "bvalue"}], 

    "results:[    // this is your 'entries' value here 
     { document_1 }, 
     { document_2 }, 
     { document_3 }, 
     .... 

所以大家都在说的是嵌入entries成你要序列化和返回另一个结构。通过尝试将其他密钥推入entries列表中,您正在以错误的方式进行操作。