2014-09-03 59 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)