如何在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
相关产品推荐
相关产品推荐

