MongoDB如何从section_information嵌套对象中提取row_cells数组
MongoDB嵌套动态键数组提取方案
方法1:Python侧本地处理(优先推荐,实现简单)
拿到查询返回的section_information字段后,遍历其所有属性值提取row_cells即可:
cur = collection.find_one({"filename":"172977114"}, {"section_information": 1}) all_row_cells = [] section_info = cur.get("section_information", {}) # 遍历所有动态键(0_0、1_0等)对应的对象 for section_item in section_info.values(): if "row_cells" in section_item: # 追加单个row_cells数组,如需合并为一维数组可把append改为extend all_row_cells.append(section_item["row_cells"])
方法2:MongoDB聚合查询直接提取(适合数据量大的场景)
通过聚合管道直接在数据库层面完成提取,无需拉取完整的section_information到本地:
pipeline = [ # 匹配目标文档 {"$match": {"filename": "172977114"}}, # 将嵌套对象转为键值对数组,适配动态键场景 {"$project": {"section_arr": {"$objectToArray": "$section_information"}, "_id": 0}}, # 拆分数组为单条记录 {"$unwind": "$section_arr"}, # 提取row_cells字段 {"$project": {"row_cells": "$section_arr.v.row_cells"}} ] # 执行查询,结果为所有row_cells的集合 result = list(collection.aggregate(pipeline))
内容的提问来源于stack exchange,提问作者Naveen Gabriel
相关产品推荐
相关产品推荐

