【发布时间】:2019-09-14 01:47:42
【问题描述】:
我正在使用 pymongo 查询一个集合:
import pymongo
client = pymongo.MongoClient('0.0.0.0', 27017)
db = client.documents
collection = db.collections
test_data = collection.find_one({'metadata.encodingStage.terms.data.line.data.account.shortDescription': {'$exists': True}},
{'metadata.encodingStage.terms.data.line.data.account.shortDescription': 1})
我在这里使用find_one 进行说明,但实际上这是对整个集合的find 查询。
这给出了以下输出:
{'_id': ObjectId('5a2fb9371de46756df51f37b'),
'metadata': {'encodingStage': {'terms': {'data':
{'line': [{'data': {'account': {'shortDescription': ['123456']}}},
{'data': {'account': {'shortDescription': ['7890123']}}}]}}}}}
但是,我想要表格格式的数据,按照 SQL 或 Pandas:
_id shortDescription
-------------------------------------------------------
ObjectId('5a2fb9371de46756df51f37b') 123456
ObjectId('5a2fb9371de46756df51f37b') 7890123
我了解如何在 Python 中执行此操作,循环遍历结果,但为了计算效率,我希望更多的制表在 Mongo 中发生。
有没有一种简单的方法可以使用 pymongo 将结果输出为{'_id': 'XXX', 'shortDescription': 'XXX') 对,可以有效地制表?
展开聚合?
我已尝试将其作为 $unwind 聚合:
unwind = collection.aggregate([{'$unwind': '$metadata.encodingStage.terms.data.line.data.account.shortDescription'}])
...但这不会返回任何数据。
【问题讨论】:
标签: python mongodb pandas pymongo