You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:36:05