Python 解析键:列表中的值对

Python 解析键:列表中的值对,python,pymongo,Python,Pymongo,我继承了一个Mongo结构,在一个数组中包含key:value对。我需要在下面的标记中提取收集的和花费的值,但是我看不到使用Mongo查询文档中的$regex命令来实现这一点的简单方法 { "_id" : "94204a81-9540-4ba8-bb93-fc5475c278dc" "tags" : ["collected:172", "donuts_used:1", "spent:150"] } 提取这些值的理想输出是在使用pymongo查询它们时将它们转储为

我继承了一个Mongo结构,在一个数组中包含key:value对。我需要在下面的标记中提取收集的和花费的值,但是我看不到使用Mongo查询文档中的$regex命令来实现这一点的简单方法

    {
    "_id" : "94204a81-9540-4ba8-bb93-fc5475c278dc"
    "tags" : ["collected:172", "donuts_used:1", "spent:150"]
    }
提取这些值的理想输出是在使用pymongo查询它们时将它们转储为以下格式。我真的不知道如何最好地只返回我需要的值。请告知


94204a81-9540-4ba8-bb93-fc5475c278dc,172150

如果您在编写mongo查询时遇到困难(列表中的元素实际上是字符串,而不是需要解析的键值),下面是一个简单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()
,您可以在此处使用适当的函数检索所有记录,并浏览每个记录。我不确定您的数据是否一致,所以我使用列表中的第一个和第三个元素硬编码。。。您可以调整该部分,并尝试除记录级别之外的其他功能

这里是一种方法,如果您所拥有的只是示例JSON对象

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
请注意关于标记顺序等的注释。最好修改您的“模式”,以便您可以更轻松地查询、收集和聚合您所称的“标记”

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)

我将把记录读入python,然后在python中查询特定元素,而不是编写疯狂的mongo查询,如果可以的话,也许我可以想出一个解决方案。