Home > OS >  How to add the index number from the array in MongoDB
How to add the index number from the array in MongoDB

Time:09-25

Explanation: How I can add the index of the array. please check the expected output, I have that array 10000 elemets

[
    {
    "data": [
        [
          1000
        ],
        [
          20
        ],
        [
          300
        ],
        [
          40
        ]
      ]
    }
  ]

The expected output will be with the index number.

{
    "data": [{
            "value": 1000,
            "Index": 1
        },
        {
            "value": 20,
            "Index": 2
        },
        {
            "value": 300,
            "Index": 3
        },
        {
            "value": 40,
            "Index": 4
        }
    ]
}

CodePudding user response:

Would be this one:

db.collection.aggregate([
   {
      $set: {
         data: {
            $map: {
               input: { $range: [0, { $size: "$data" }] },
               as: "idx",
               in: {
                  index: { $add: ["$$idx", 1] },
                  value: { $first: { $arrayElemAt: ["$data", "$$idx"] } }
               }
            }
         }
      }
   }
])

Mongo Playground

  • Related