Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB run loop to add incremental index value in low size array

I have a MongoDB collection where I have an array of objects (low size) 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. Data :

  db="abc" : {
    "array": [
      {
        "_id": "a",
        "timestamp": "t1",
        "type": "object"
      }
     ]
   }


db.collection.aggregate([
    {
        "$unwind": "$array"
    },
    {
        "$addFields": {
            "array.index": {
                "$add": [
                    {
                        "$ifNull": ["$index", 0]
                    },
                    1
                ]
            }
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "array": {
                "$push": "$$ROOT.array"
            }
        }
    }
])
like image 905
programmer01 Avatar asked Nov 23 '25 13:11

programmer01


1 Answers

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.

like image 124
Aniket Raj Avatar answered Nov 25 '25 11:11

Aniket Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!