skip to Main Content

I have a MongoDB collection where I have an array of objects and I want to add an incremental index value to each element of the array of objects.

Like index starts from 0 to array length – 1.

db.collection.aggregate([
    {
        "$unwind": "$array"
    },
    {
        "$addFields": {
            "array.index": {
                "$add": [
                    {
                        "$ifNull": ["$index", 0]
                    },
                    1
                ]
            }
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "array": {
                "$push": "$$ROOT.array"
            }
        }
    }
])

2

Answers


  1. MongoDB playground link: https://mongoplayground.net/p/SWw7rIYHNcj

    db.collection.aggregate([
      {
        "$unwind": {
          "path": "$array",
          "includeArrayIndex": "index"
        }
      },
      {
        "$addFields": {
          "array.index": {
            "$toInt": "$index"
          }
        }
      },
      {
        "$group": {
          "_id": "$_id",
          "array": {
            "$push": "$$ROOT.array"
          }
        }
      }
    ])
    

    $unwind stage:
    Opens an array field ($array) from the input documents.
    Creates a new document for each element in the array.
    Includes the array index of each element in a new field using includeArrayIndex.

    $addFields stage:
    Adds a new field ("array.index") to each document.
    Converts the "index" field to an integer using the $toInt operator..

    $group stage:
    Groups documents based on the "_id" field.
    Creates an "array" field within each group using the $push operator.

    Login or Signup to reply.
  2. Here’s another way to do it. Comments are in the pipeline.

    db.collection.aggregate([
      { // just add index if type is array
        "$match": {
          "array": {"$type": "array"}
        }
      },
      { // map each element with incremental index
        "$set": {
          "array": {
            "$map": {
              "input": {
                // produce index values
                "$range": [0, {"$size": "$array"}]
              },
              "as": "idx",
              "in": {
                // merge index into each object
                "$mergeObjects": [
                  {"index": "$$idx"},
                  {"$arrayElemAt": ["$array", "$$idx"]}
                ]
              }
            }
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search