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

MongoDB中如何投影嵌套数组指定索引位置字段的$type数据类型

MongoDB多层嵌套数组指定索引字段类型查询方案

针对已知多层数组索引、需要获取对应位置字段类型的需求,可直接通过聚合框架的$arrayElemAt操作符实现,无需使用$elemMatch等查询操作符。

具体查询语句

兼容MongoDB 5.0+版本(语法更简洁)

db.your_collection_name.aggregate([
  {
    $project: {
      type: {
        $type: {
          $getField: {
            field: "reference",
            input: {
              $arrayElemAt: [
                { $getField: { field: "metaData", input: { $arrayElemAt: ["$series", 1] } } },
                0
              ]
            }
          }
        }
      }
    }
  }
])

兼容MongoDB 4.2及更早版本

db.your_collection_name.aggregate([
  {
    $project: {
      type: {
        $type: {
          $let: {
            vars: {
              // 取series数组索引为1的元素
              targetSeries: { $arrayElemAt: ["$series", 1] },
              // 取该元素下metaData数组索引为0的元素
              targetMeta: { $arrayElemAt: ["$$targetSeries.metaData", 0] }
            },
            // 返回reference字段,外层$type直接取该字段类型
            in: "$$targetMeta.reference"
          }
        }
      }
    }
  }
])

返回结果示例

和预期格式完全一致:

{ "_id": "12345", "type": "double" }

如果需要查询其他索引位置的字段类型,直接替换$arrayElemAt的第二个参数为目标索引值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:39:02