2014-09-03 50 views
0

我已經在數組中使用鍵:值對繼承了Mongo結構。我需要在下面的標籤中提取收集和使用的值,但是我沒有看到使用Mongo Query文檔中的$ regex命令執行此操作的簡單方法。解析鍵:值列表中的值對

{ 
    "_id" : "94204a81-9540-4ba8-bb93-fc5475c278dc" 
    "tags" : ["collected:172", "donuts_used:1", "spent:150"] 
    } 

提取這些值的理想輸出是將它們轉儲到使用pymongo查詢時它們下面的格式。我真的不知道如何才能最好地返回我需要的值。請指教。

94204a81-9540-4ba8-bb93-fc5475c278dc,172,150

+0

我會將記錄讀入python,然後在Python中查詢某個元素,而不是編寫瘋狂的mongo查詢,如果沒關係,也許我可以找出解決方案。 – 2014-09-03 16:32:59

回答

1
print d['_id'], ' '.join([ x.replace('collected:', '').replace('spent:', '')\ 
    for x in d['tags'] if 'collected' in x or 'spent' in x ]) 
>>> 
94204a81-9540-4ba8-bb93-fc5475c278dc 172 150 
1

如果你有困難的時間寫蒙戈查詢(名單內的元素實際上是字符串,而不是鍵值需要解析),這裏是一個純Python的解決方案,可能會有所幫助。

>>> import pymongo 
>>> from pymongo import MongoClient 
>>> client = MongoClient('localhost', 27017) 
>>> db = client['test'] 
>>> collection = db['stackoverflow'] 
>>> collection.find_one() 
{u'_id': u'94204a81-9540-4ba8-bb93-fc5475c278dc', u'tags': [u'collected:172', u'donuts_used:1', u'spent:150']} 
>>> record = collection.find_one() 
>>> print record['_id'], record['tags'][0].split(':')[-1], record['tags'][2].split(':')[-1] 
94204a81-9540-4ba8-bb93-fc5475c278dc 172 150 

而不是使用find_one()的,你可以在此使用相應的功能檢索所有記錄,並通過各種記錄德路。我不確定數據的一致性如何,所以我使用列表中的第一個和第三個元素進行硬編碼......您可以調整該部分並嘗試除記錄級別之外的其他部分。

0

以下是一種方法,如果您只有樣本JSON對象。

請注意關於標籤排序的說明等。最好修改您的「架構」,以便您可以在調用它們時更輕鬆地查詢,收集和彙總「標籤」。

import re 

# Returns csv string of _id, collected, used 
def parse(obj): 
    _id   = obj["_id"] 
    # This is terribly brittle since the insertion of any other type of tag 
    # between 'c' and 's' will cause these indices to be messed up. 
    # It is probably much better to directly query these, or store them as individual 
    # entities in your mongo "schema". 
    collected = re.sub(r"collected:(\d+)", r"\1", obj["tags"][0]) 
    spent  = re.sub(r"spent:(\d+)", r"\1", obj["tags"][2]) 
    return ", ".join([_id, collected, spent]) 

# Some sample object 
parse_me = { 
    "_id" : "94204a81-9540-4ba8-bb93-fc5475c278dc" 
    "tags" : ["collected:172", "donuts_used:1", "spent:150"] 
} 
print parse(parse_me)