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

如何获取MongoDB集合中数组内嵌的字段名

MongoDB全字段(含内嵌数组字段)提取方案

适配单层内嵌数组的专用方案

针对你提供的样本数据结构,可直接使用以下聚合查询,返回结果会包含顶层字段和数组内的内嵌字段:

db.getCollection('appd_application_master').aggregate([
  // 提取所有顶层字段
  {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
  {"$unwind":"$arrayofkeyvalue"},
  {"$group":{"_id":null,"topKeys":{"$addToSet":"$arrayofkeyvalue.k"}, "docs": {"$push": "$$ROOT"}}},
  {"$unwind":"$docs"},
  // 筛选出数组类型的字段做处理
  {"$match": {"docs.arrayofkeyvalue.v": {"$type": "array"}}},
  {"$unwind": "$docs.arrayofkeyvalue.v"},
  // 转换数组内对象为键值对,拼接父级字段名生成完整字段路径
  {"$project": {
    "parentKey": "$docs.arrayofkeyvalue.k",
    "nestedKV": {"$objectToArray": "$docs.arrayofkeyvalue.v"}
  }},
  {"$unwind": "$nestedKV"},
  {"$project": {
    "fullKey": {"$concat": ["$parentKey", ".", "$nestedKV.k"]}
  }},
  // 合并顶层字段和内嵌字段,自动去重
  {"$group": {
    "_id": null,
    "nestedKeys": {"$addToSet": "$fullKey"},
    "topKeys": {"$first": "$topKeys"}
  }},
  {"$project": {
    "allKeys": {"$setUnion": ["$topKeys", "$nestedKeys"]},
    "_id": 0
  }}
])

针对你的样本数据,该查询返回的allKeys会新增mapSvnFilesMst._id、mapSvnFilesMst.commitAction两个内嵌字段,符合预期需求。

适配任意深度嵌套的通用方案

如果你的集合存在多层嵌套的对象、数组结构,可使用MongoDB 4.4及以上版本支持的$function自定义递归逻辑,自动遍历所有层级提取字段:

db.getCollection('appd_application_master').aggregate([
  {
    "$project": {
      keys: {
        $function: {
          body: function(doc) {
            const keys = [];
            // 递归遍历所有层级的字段
            const traverse = (obj, prefix = '') => {
              Object.keys(obj).forEach(key => {
                const fullKey = prefix ? `${prefix}.${key}` : key;
                keys.push(fullKey);
                const val = obj[key];
                // 处理数组类型
                if (Array.isArray(val)) {
                  val.forEach(item => {
                    if (typeof item === 'object' && item !== null) {
                      traverse(item, fullKey);
                    }
                  })
                // 处理嵌套对象,排除MongoDB内置的ObjectId、Date类型
                } else if (typeof val === 'object' && val !== null && !(val instanceof ObjectId) && !(val instanceof Date)) {
                  traverse(val, fullKey);
                }
              })
            }
            traverse(doc);
            // 单条记录内字段去重
            return [...new Set(keys)];
          },
          args: ["$$ROOT"],
          lang: "js"
        }
      }
    }
  },
  // 拆分字段数组后全集合去重
  {"$unwind": "$keys"},
  {"$group": {"_id": null, "allKeys": {"$addToSet": "$keys"}}}
])

内容的提问来源于stack exchange,提问作者xxx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:36:00