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

如何在MongoDB小尺寸对象数组中添加从0开始的递增索引

给MongoDB数组内对象添加从0起始的递增索引

正确实现方案(高效版)

因为你的数组尺寸较小,推荐直接使用$map结合$range和$zip的方式,无需拆分再聚合,性能更优:

示例数据

{
  "_id": "doc1",
  "array": [
    {
      "_id": "a",
      "timestamp": "t1",
      "type": "object"
    },
    {
      "_id": "b",
      "timestamp": "t2",
      "type": "object"
    }
  ]
}

聚合管道代码

db.collection.aggregate([
  {
    "$addFields": {
      "array": {
        "$map": {
          // 将数组元素与0起始的索引序列配对
          "input": { "$zip": { "inputs": ["$array", { "$range": [0, { "$size": "$array" }] }] } },
          "as": "pair",
          // 合并原对象和索引字段
          "in": { "$mergeObjects": ["$$pair.0", { "index": "$$pair.1" }] }
        }
      }
    }
  }
])

如果数组内不存在重复对象,也可以用$indexOfArray简化:

db.collection.aggregate([
  {
    "$addFields": {
      "array": {
        "$map": {
          "input": "$array",
          "as": "item",
          "in": {
            "$mergeObjects": [
              "$$item",
              { "index": { "$indexOfArray": ["$array", "$$item"] } }
            ]
          }
        }
      }
    }
  }
])

你当前代码的问题

  • 代码中引用的$index字段不存在,$ifNull会始终返回0,导致所有对象的index都被设为1,无法生成递增序列。
  • $unwind操作拆分数组后,没有保留元素的原始位置信息,后续通过累加的方式无法得到正确的索引值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 19:12:25