2012-08-14 44 views
2

當我下面的文件存儲到蒙戈,是這樣的:用pongongo從mongo中檢索文檔時的排序屬性?

{ 
name: Somename, 
profile: Someprofile 
} 

當我使用一個find_one():

我得到的是這樣一個結果:

{ 
profile: Someprofile, 
_id: 35353432326532(random mongo id), 
name: Somename 
} 

有python中的某種方式,使得當我在find_one之前或之後執行某些操作時,可以得到如下排序的json字符串的結果:

{ 
_id: 35353432326532(random mongo id), 
name: Somename, 
profile: Someprofile 
} 

我試過使用下面的OrderedDict,但它似乎沒有幫助。

somedocument = db.mycollection 
theordereddict = OrderedDict(data_layer.find_one()) 
print str(theordereddict) 

如何獲得我的輸出字符串以正確的順序關於屬性?在我甚至將文檔插入數據庫之前,這個命令是否由別的東西決定了?

+0

什麼是你想要依靠在JSON文檔中字段的順序上的原因嗎?因爲他們被命名,你可以通過關鍵名稱引用他們,而不用擔心訂單... – 2012-08-14 21:09:45

+0

不錯的閱讀:http://code.activestate.com/recipes/52306-to-sort-a-dictionary/ – 2012-08-14 21:49:00

回答

0

collections.OrderedDict不按順序鍵它只是保留順序,您需要按照您想要檢索它們的順序插入鍵。

d = data_layer.find_one() 
def key_function(tuple): 
    """This defines the sort order for the sorted builtin""" 
    return tuple[0] 
sorted_dict = collections.OrderedDict((k,v) for k, v in sorted(d.items(), 
                   key=key_function))  

這就是說,它看起來像print str(sorted_dict)不給你你想要的輸出。我認爲你需要手動建立你的排序字符串表示。例如: -

s = "{" + ",".join(["%s:%s" for k,v in sorted(d.items(), key=key_function)]) + "}" 
+0

什麼是「lambda」和它後面的語法是什麼意思? – Rolando 2012-08-14 21:22:19

+0

'lambda'定義了一個匿名函數,它與我更新的答案中的'key_function'相當。重要的部分是使用一個函數來定製由'sorted'內建執行的排序。 – stderr 2012-08-14 21:42:24

0

基本上一樣@Mike Steder的答案,但也許更少幻想和更加清晰:

import json 
from collections import OrderedDict 

theordereddict = OrderedDict() 
d = data_layer.find_one() 
for k in sorted(d.keys()): 
    theordereddict[k] = d[k] 

json.dumps(theordereddict)