如何从 mongodb 中的集合中获取完整的键列表

how to get full list of keys from a collection in mongodb

如何获取 mongodb 集合中使用的所有键的列表?

我正在尝试使用以下方法在 python 中创建一个 csv 文件:

userAgentProp_list = []
# userAgentProp is a set of user ids
# userColl is a mongodb collection
for user in userAgentProp:
    userAgentProp_list.append(userColl.find_one({"_id":user}))

with open('userWtihAgentProp.csv','w+') as f:
    w = csv.DictWriter(f,userAgentProp_list[0].keys())
    w.writeheader()
    for user in userAgentProp_list:
        # del row['_id']
        w.writerow(user)

但我一直收到错误消息:

ValueError: dict contains fields not in fieldnames

我认为这是因为 userAgentProp_list[0] 与集合中其他文档的字段不完全相同。

如何获取集合中使用的所有键的列表?

我想我想出了一个解决方案。我希望有更多经验的人告诉我这是否正确 and/or 可以有效地完成 better/more。

def getCollectionKeys(collection):
    """Get a set of keys from a collection"""
    keys_list = []
    collection_list = collection.find()
    for document in collection_list:
        for field in document.keys():
            keys_list.append(field)
    keys_set =  set(keys_list)
    return keys_set